如何使用“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.
例如
{% if foo.paid %}
{% include "foo/customization/{{ foo.id }}.html" %}
{% endif %}
这可能吗?因为 foo.id 在 includes 标签起作用之前没有被翻译.结果它给出了一个错误.如何以不同的方式处理这个问题?我应该为此创建一个自定义模板标签吗?
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 ?
推荐答案
{% if foo.paid %}
{% with template_name=foo.id|stringformat:"s"|add:".html" %}
{% include "foo/customization/"|add:template_name %}
{% endwith %}
{% endif %}
首先构建一个 template_name
,它由字符串格式的 foo.id
和 .html
组成.然后将其传递给 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屋!