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

Is django can modify variable value in template?

我想编写一个只渲染一次的模板。

我的想法是创建一个标志变量来检查它是第一次。

我的代码

{% with "true" as data %}
    {% if data == "true" %}
        //do something
        ** set data to "false" **
    {% else %}
        //do something
    {% endif %}
{% endwith %}

我不知道如何在django模板中更改变量。这可能吗?或者有更好的方法吗?

这可以通过 Django 自定义过滤器来完成

django custom filter

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 %}

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

@register.simple_tag
def update_variable(value):
    """Allows to update existing variable in template"""
    return value

然后像这样使用它:

{% with True as flag %}
    {% if flag %}
        //do somethings
        {% update_variable False as flag %}
    {% else %}
        //do somethings
    {% endif %}
{% endwith %}