0

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.

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
fabrice
  • 1,399
  • 1
  • 15
  • 27

1 Answers1

0

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>
Daniel
  • 3,228
  • 1
  • 7
  • 23
  • So, after the {% endwith %} tag, the variable is not set. In my example, I can't retreive the value :( – fabrice Sep 23 '21 at 07:24
  • But, for now, in my first message, I don't understand why the value, after the loop, is empty. Any idea please ?. Thanks – fabrice Sep 23 '21 at 07:25
  • This is likely not a coding error but a logic error. What should the value of `selected_status` be outside of the if statement? – Daniel Sep 23 '21 at 13:15