1

在 Django 模板中,可以使用标签在上下文中引入一个新的命名变量with

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

我发现自己经常使用它来重命名变量,以便可以包含可重用的模板:

{% with user_list=request.user.friends %}
    {% include '_user_list.html' %}
{% endwith %}

有没有办法在不使用with标签的情况下在上下文中引入新变量?我正在想象一个标签set,就像你曾经调用它一样{% set user_list=request.user.friends %},然后不需要用{% endset %}标签关闭它。这类似于{% trans "This is the title" as the_title %}in 函数。

如果没有办法做到这一点,那么这不是一个好的 / pythonic / django 做事方式的一些原因是什么?

4

1 回答 1

3

如果您查看include模板标签,您会发现您可以在标签本身内将变量分配和传递给模板:

您可以使用关键字参数将其他上下文传递给模板:

{% include "name_snippet.html" with person="Jane" greeting="Hello" %}
于 2013-05-02T10:45:17.770 回答