开发者

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

开发者 https://www.devze.com 2023-02-03 16:32 出处:网络
I\'d like to use an {% include page.html %} tag in my Django template, and construct the value of page.html dynamically.

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 pseudo开发者_StackOverflow社区code example:

{% include page_{{mode}}.html %}

Thanks!


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.


I think that goliney provided a better answer here

In summary:

You can combine django's built-in 'with' template tag to assign a dynamically constructed template name to a variable and the 'add' filter and to dynamically construct a template name.

For example:

 {% with template_name='page_'|add:mode|add:".html" %}
     {% include ""|add:template_name %}
 {% endwith %}


You can concatenate plain strings and variables right in your templates using with tag and add filter, see this SO answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号