Is django can modify variable value in template?

牧云@^-^@ 提交于 2019-12-05 06:31:09
NIKHIL RANE

This can be done with a Django custom filter

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's answer doesn't work for me. Custom simple_tag() can be used to do the job:

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

and then use it like this:

{% with True as flag %}
    {% if flag %}
        //do somethings
        {% update_variable False as flag %}
    {% else %}
        //do somethings
    {% endif %}
{% endwith %}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!