I'd like to use an {% include page.html %}
tag in my Django template, and construct the value of page.html
dynamically.
Is there any way to do this in Django?
Here's a pseudocode example:
{% include page_{{mode}}.html %}
Thanks!
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.
{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in 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.
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.
From the docs:
The template name can either be a variable or a hard-coded (quoted) string, in either single or double quotes.
So construct a variable in your view and pass it to your template via the context, say as 'modeTemplate': "page_"+mode+".html". Then do:
{% include modeTemplate %}
Assuming 'mode' is a python variable in your view code.
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