Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include templates dynamically in Django using "include" tag

I have 10 html files with the names 1.html, 2.html ..etc What I want is according to a variable, a certain file should be included in the template.

e.g.

{% if foo.paid %}
    {% include "foo/customization/{{ foo.id }}.html" %}
{% endif %}

Is this possible ? Cause the foo.id is not being translated before the includes tag works. As a result its giving a error. How can this issue be handled in a different way ? Should I create a custom template tag for this ?

like image 208
Akash Deshpande Avatar asked Oct 01 '12 08:10

Akash Deshpande


People also ask

What is with tag in Django template?

Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client. In the next chapters you will learn about the most common template tags.

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

How do I add a template to Django?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.

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.


1 Answers

You can do it with add filter and with statement .

{% if foo.paid %}     {% with template_name=foo.id|stringformat:"s"|add:".html" %}         {% include "foo/customization/"|add:template_name %}     {% endwith %} {% endif %} 

First you build a template_name, which consist of foo.id in string format concatenated with .html. Then you pass it to include tag, concatenated with path to template directory.

like image 184
Serhii Holinei Avatar answered Sep 23 '22 14:09

Serhii Holinei