django可以修改模板中的变量值吗?

Wir*_*ang 6 django django-templates

我想写一些只能渲染一些东西的模板.

我的想法是创建标志变量,以便检查它是否是第一次?

我的代码

{% with "true" as data %}
    {% if data == "true" %}
        //do somethings
        ** set data to "false" **
    {% else %}
        //do somethings
    {% endif %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)

我不知道如何在django模板中更改变量?(可能吗 ?)

要么

更好的方法来做到这一点.

谢谢

pol*_*art 8

NIKHIL RANE 的答案对我不起作用。自定义simple_tag()可以用来完成这项工作:

@register.simple_tag
def update_variable(value):
    """Allows to update existing variable in template"""
    return value
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

{% with True as flag %}
    {% if flag %}
        //do somethings
        {% update_variable False as flag %}
    {% else %}
        //do somethings
    {% endif %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)


NIK*_*ANE 7

这可以使用django自定义过滤器完成

django自定义过滤器

def update_variable(value):
    data = value
    return data

register.filter('update_variable', update_variable)

{% with "true" as data %}
    {% if data == "true" %}
        //do somethings
        {{update_variable|value_that_you_want}}
    {% else %}
        //do somethings
    {% endif %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)

  • 如果我不想打印该变量怎么办? (2认同)