Wiriya Rungruang
Wiriya Rungruang

Reputation: 318

Is django can modify variable value in template?

I want to write a template that renders something only one time.

My idea is to create a flag variable to check it is the first time.

My code

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

I don't know How to change a variable in django template. Is it possible? Or is there a better way to do this?

Upvotes: 11

Views: 25275

Answers (2)

NIKHIL RANE
NIKHIL RANE

Reputation: 4108

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

Upvotes: 10

polart
polart

Reputation: 541

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

Upvotes: 9

Related Questions