如何使用“include”在Django中动态地包含模板标签 [英] How to include templates dynamically in Django using "include" tag
问题描述
我有10个html文件,名称为1.html,2.html ..etc
我想要的是根据一个变量,某个文件应该包含在模板中。
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.
eg
{% if foo.paid %}
{% include "foo/customization/{{ foo.id }}.html" %}
{% endif %}
这可能吗?因为在include标签工作之前,foo.id没有被翻译。结果给了一个错误。这个问题如何以不同的方式处理?
我应该为此创建自定义模板标签吗?
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 ?
推荐答案
您可以使用 add filter and with statement 。
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 %}
您构建一个 template_name
,其中包含以 .html连接的字符串格式的
。然后将其传递给 foo.id
include
标记,并与模板目录的路径相连。
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.
这篇关于如何使用“include”在Django中动态地包含模板标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!