Dynamic Include Template with django

I am creating a Django website and my sidebar may have different elements for different users. So my main sidebar template has a div for each plugin to be included, and specific HTML for each of these plugins is included in their own template file.

Example:

<div id="plugins"> <div id="plugin1"> {% include 'plugin1.html' %} </div> <div id="plugin2"> {% include 'plugin2.html' %} </div> </div> 

Now I want to dynamically build this list, how can I do this? Since the template is only parsed once, so I could not send it the string {{% include "plugin1.html '}' in context

Any ideas?

+6
python django
source share
2 answers

You can use the variable inside the include tag:

 {% include my_user_html %} 
+15
source share

You can generate a variable in the view, as described above, containing your template, or you can use the template tag to create a template path for you based on another variable, i.e. phase. Register the following tag, customize it to your needs:

 @register.filter def get_template_phase(template_string, phase): template_string = template_string.replace('<', '{').replace('>', '}') return template_string.format(phase=phase) 

Put the above in your templatetags and register it.

Using:

 {% include 'includes/home__<phase>.html'|get_template_phase:'nomination' %} 
0
source share

All Articles