[Answer]-Django add {%extends%} tag in the view

1๐Ÿ‘

โœ…

Iโ€™m not sure why are you trying but you cannot put {%extends ...%} in HTML (unless you want to render it again using django templates. Adding that string to template after rendering will add unwanted {%extends ...%} string in the template.

But if you want you can create a template dynamically and render it. The new template can extend existing template.
For example:

>>> from django.template import Template, Context
>>> #creates a template from string, "base.html" can be self.base in your case
>>> t = Template('{%extends "' + "base.html" + '"%} ...') 
>>> c = Context({'your_var1': 'var1_value'})            #get context for template
>>> t.render(c)                                         #render the created template 
u'\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n
 <html xmlns="http://www.w3.org/1999/xhtml">
....

More reference at: Template Compiling a string

๐Ÿ‘คRohan

0๐Ÿ‘

The same you can achieve in django template by passing a variable template_name to template. And then in template put this code at very top.

{% with template_name|add:".html" as template %}
{% include template %}
{% endwith %}

Or see this question for more help.

๐Ÿ‘คAhsan

Leave a comment