Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: construct value of {% include %} tag dynamically?

Tags:

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!

like image 867
AP257 Avatar asked Jan 12 '11 15:01

AP257


People also ask

What {% include %} does in 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.

What does {% include %} do?

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

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.

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.


1 Answers

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.

like image 105
Spacedman Avatar answered Nov 07 '22 11:11

Spacedman