包含 Django 模板时是否可以传递变量变量

时间:2021-03-17 16:44:42

标签: django django-templates

我想使用 Django 模板在下拉按钮中创建指向未选择版本的链接。

创建的链接定义如下:

{% for release in all_releases %}
  {% if release != in_release and release != out_release %}
    <a href="{% url url_view %}?in_release={{release}}&out_release= {{out_release}}">{{release}}</a>
  {% endif %}
{% endfor %}

{% for release in all_releases %}
  {% if release != in_release and release != out_release %}
    <a href="{% url url_view %}?in_release={{in_release}}&out_release={{release}}">{{release}}</a>
  {% endif %}
{% endfor %}

是否可以创建包含以下内容的 dropdown-link.html 文件:

{% for release in all_releases %}
  {% if release != in_release and release != out_release %}
    <a href="{% url url_view %}?in_release={{in_release_query}}&out_release={{out_release_query}}">{{release}}</a>
  {% endif %}
{% endfor %}

并像这样在实际渲染的模板中调用它,有点像创建变量:

{% include "release-dropdown.html" with in_release_query=release out_release_query=out_release %}
...
{% include "release-dropdown.html" with in_release_query=in_release out_release_query=release %}

我知道这种确切的方法在这里是不可能的。您会推荐替代方案吗?

1 个答案:

答案 0 :(得分:0)

看起来你想要一个inclusion tag

您可以创建一个带有两个参数并呈现 release-dropdown.html

的标签
@register.inclusion_tag('release-dropdown.html')
def release_dropdown(in_release, out_release):
    return {
        'in_release': in_release,
        'out_release': out_release,
    }

然后在您的模板中使用变量调用它:

{{ load '<name of the template tag file>' }}
{% release_dropdown release out_release %}