【问题标题】:How to include templates dynamically in Django using "include" tag如何使用“include”标签在 Django 中动态包含模板
【发布时间】:2012-09-22 02:16:49
【问题描述】:

我有 10 个名为 1.html、2.html ..etc 的 html 文件 我想要的是根据一个变量,模板中应该包含某个文件。

例如

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

这可能吗?导致 foo.id 在包含标签工作之前没有被翻译。结果它给出了一个错误。如何以不同的方式处理这个问题? 我应该为此创建一个自定义模板标签吗?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    您可以使用 add filterwith statement 来做到这一点。

    {% 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 标签,并与模板目录的路径连接。

    【讨论】:

      猜你喜欢
      • 2011-04-25
      • 2013-06-05
      • 1970-01-01
      • 2021-08-29
      • 2013-10-17
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多