I would like to have a template that extends another conditionally. Basically, when a variable called "ajax" is true I DO NOT want to have the template extend another.
{% if not ajax %} {% extends "/base.html" %} {% endif %}
Any clues?
Answer and Explanation: Answer: (b) {% . In Django the template tag is surrounding by {% .
This tag can be used in two ways: {% extends "base.html" %} (with quotes) uses the literal value "base.html" as the name of the parent template to extend. {% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template.
{% endblock %} </div> </body> </html> In this example, the {% block %} tags define four blocks that child templates can fill in. All the block tag does is tell the template engine that a child template may override those portions of the template.
The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output. One can use various boolean operators with Django If Template tag.
While you may not wrap extends
in logic blocks, since it must be the first tag if used, it can still accept variables, including filters. This should fit your purpose nicely:
{% extends ajax|yesno:"base_ajax.html,base.html" %} {# stuff #}
Note: the yesno
filter also accepts null values (None
) as the third choice, and if you do not specify one (as in this case), it will fallback to converting it to False
(i.e. it will return the second choice). This allows you to not specify the ajax
variable in your template without breaking it.
Suggested by user Rafael:
{% extends request.is_ajax|yesno:"base_ajax.html,base.html" %} {# stuff #}
This will only work if you are using a RequestContext
context instead of a plain Context
object and you have the request
context processor enabled, or alternatively, if you insert the request object in your template context.
You cannot do it like that. You can however set a variable and use that to choose the template to extend:
{% extends my_template %}
Then in python code you write something like:
if ajax: template_values['my_template'] = 'base_ajax.html' else: template_values['my_template'] = 'base.html'
You may wish to refer to the documentation for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With