Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to make {% extends '...' %} conditional? - Django

I would like to share a template between AJAX and regualr HTTP calls, the only difference is that one template needs to be served with the base.html html, the other one without.

Any idea?

like image 508
RadiantHex Avatar asked Mar 21 '11 16:03

RadiantHex


People also ask

What does {% include %} does Django?

From the documentation: {% 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. If the variable evaluates to a Template object, Django will use that object as the parent template.

Why is {% extends %} tag used?

The extends tag is used to declare a parent template. It should be the very first tag used in a child template and a child template can only extend up to one parent template. To summarize, parent templates define blocks and child templates will override the contents of those blocks.

Can you extend more than one template Django?

Yes you can extend different or same templates.

When {% extends %} is used for inheriting a template?

extends tag is used for inheritance of templates in django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables.


2 Answers

The other answers require you to pass an additional context variable. But as long as you can access the request object, there is no need:

{% extends request.is_ajax|yesno:"app/base_ajax.html,app/base.html" %} 

I found this to be much more convenient.

like image 88
Cruel Avatar answered Sep 21 '22 00:09

Cruel


Use a variable.

{% extends base_template %} 

and in your view, set it to "base.html" in your view, or a new "ajax.html" file which just provides the block and nothing else.

like image 33
Daniel Roseman Avatar answered Sep 19 '22 00:09

Daniel Roseman