Assign a value to a variable already declared in the template in django?

348 Views Asked by At

I googled but unable to find the solution. Where I went thought some answers like This answer
Some official docs which I went through Trans Tag Built-In Tags

Template View

{% load custom_tags %}

{% for each in content %}
  {% with tempID='' %} # It is initially empty string
    {% if each.contentID != tempID %}
      {% tempID = each.contentID %} # Want to assign new value to tempID
        ....
         ..
    {% endif %}
  {% endwith %}
{% endfor %}

Is there any method to assign with tag variable. I tried custom_tags filters also. Not worked.

I don't want to repeat ID Name

1

There are 1 best solutions below

6
AzyCrw4282 On

Is there any method to assign with tag variable?

Yes, you can simply use the {% with tempID= each.contentID %} which in this case will assign a new value to the variable.

Alternative

Variables in templates are merely used to display values and are not often used in a way in which calculation or reassignment is performed. In such cases though you can solve it by using a Django custom filter. See the example below.

.py file - Assign a value to a variable

@register.filter(name='update_variable')
def update_variable(value):
    data = value
    return data

.HTML file

{% with "true" as data %}
    {% if data == "true" %}
        //do somethings
        {{update_variable|value_that_you_want}}
    {% else %}
        //do somethings
    {% endif %}
{% endwith %}

Note that when you are using Django filters the variable instance resides in Python and not directly in the Template.