Can django change the value of a variable in a template?

I want to write a template that displays somethings only once.

My ideas is this create flag variable to check if this is the first time or not?

My code

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

      

I don't know How to change a variable in a django template? (is it possible?)

or

The best way to do it.

thank

+3


source to share


2 answers


This can be done with a custom django 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 %}

      

+4


source


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

      

0


source







All Articles