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?
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.
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.
Yes you can extend different or same templates.
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.
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.
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.
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