Custom tag to set a variable in Django template. Emptying the value out of context?

386 Views Asked by At

In my Django Template I want to set a variable, to use in a html tag. But, when I'm out the for loop, the variable is empty :(

{% load custom_template_tag %}

<select>
    <option value=""></option>
    {% for a_status in status %}
        {% for r in all_status_ressources %}
            {% if a_ressource.id == r.0 and a_status.name == r.1 %}
                {% setvar "selected" as selected_status %}
                id ressource : {{ r.0 }}, name status : {{ r.1 }} -> [{{ selected_status }}]<br>
            {% endif %}
                selected_status : "{{ selected_status }}"
        {% endfor %}
        end loop ---------> selected_status : "{{ selected_status }}"
        <option value="{{ a_status.id }}" selected="{{ selected_status }}">{{ a_status.name }}</option>
    {% endfor %}
</select>

The custom tag itself :

from django import template

register = template.Library()


@register.simple_tag
def setvar(val=None):
    return val

And, now the debug trace :

selected_status : ""

id ressource : 2, name status : "my personnal status" -> [selected]

selected_status : "selected"
selected_status : "selected"
selected_status : "selected"
selected_status : "selected"
selected_status : "selected"
selected_status : "selected"
selected_status : "selected"
selected_status : "selected"
selected_status : "selected"
selected_status : "selected"
selected_status : "selected"
selected_status : "selected"
selected_status : "selected"
selected_status : "selected"

end loop ---------> selected_status : ""

So, when I'm out of the for loop, the varible is not set to be used in the html tag.

1

There are 1 best solutions below

3
Daniel On

You can use the built in {% with <var>=<val> %} tag:

Something like:

template.html

<select>
  <option value=""></option>
  {% for a_status in status %}
    {% for r in all_status_ressources %}
      {% if a_ressource.id == r.0 and a_status.name == r.1 %}
        {% with selected_status="selected" %}
          id ressource : {{ r.0 }}, name status : {{ r.1 }} -> [{{selected_status }}]<br>
        {% endwith %}
      {% endif %}
      selected_status : "{{ selected_status }}"
    {% endfor %}
    end loop ---------> selected_status : "{{ selected_status }}"
    <option value="{{ a_status.id }}" selected="{{ selected_status }}">{{a_status.name }}</option>
  {% endfor %}
</select>