Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python / Django - If statement in template around extends

Tags:

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?

like image 980
GregL83 Avatar asked Feb 18 '11 15:02

GregL83


People also ask

What characters surround the template tag in Django?

Answer and Explanation: Answer: (b) {% . In Django the template tag is surrounding by {% .

What does {% %} mean in Django?

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.

What does {% endblock %} mean?

{% 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.

How can check Boolean value in if condition Django?

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.


2 Answers

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.

like image 77
sleblanc Avatar answered Nov 05 '22 04:11

sleblanc


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.

like image 45
Klaus Byskov Pedersen Avatar answered Nov 05 '22 04:11

Klaus Byskov Pedersen