假设我有一个模板

<html>
<div>Hello {{name}}!</div>
</html>

在测试它时,在不涉及调用该模板的python代码的情况下定义变量的值会很有用。所以我在找这样的东西

{% set name="World" %}     
<html>
<div>Hello {{name}}!</div>
</html>

Django中存在这样的东西吗?


当前回答

使用with语句。

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

我不能在这个回答中暗示第一段的代码。也许模板语言已经弃用了旧格式。

其他回答

也许在2009年的时候,默认的模板过滤器并不是一个选项……

<html>
<div>Hello {{name|default:"World"}}!</div>
</html>

你可以使用with template标签。

{% with name="World" %}     
<html>
<div>Hello {{name}}!</div>
</html>
{% endwith %}

在你的模板中,你可以这样做:

{% jump_link as name %}
{% for obj in name %}
    <div>{{obj.helo}} - {{obj.how}}</div>
{% endfor %}

在你的模板标签中,你可以添加一个这样的标签:

@register.assignment_tag
def jump_link():
    listArr = []
    for i in range(5):
        listArr.append({"helo" : i,"how" : i})
    return listArr

使用with语句。

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

我不能在这个回答中暗示第一段的代码。也许模板语言已经弃用了旧格式。

有些把戏就像约翰描述的那样;然而,Django的模板语言在设计上不支持设置变量(参见Django文档中的模板“Philosophy”框)。 因此,更改任何变量的建议方法是通过触摸Python代码。