jinja2html-select

jinja2 if else in select tag


        <select class="form-control" id="types" name="types" combojs="types">
            {% for t in tdata %}
            <option value="{{ t[0] }}" {% if t[0] == t1is %} selected {% endif %}>
                {{ t[0] }}
            </option>
            {% endfor %}
        </select>

I use python flask render_template to pass tdata as list, and t1is as selected. This works for a drop down combobox, with the t1is being the selected option displayed, but can I also set a default if not selected with t1is. I tried to put {% else t[0] == "None" %} after selected, but I don't have any idea if it is right syntax. And of course it does not work. The first item is displayed if nothing selected. Do I need to make the default item first in list.


Solution

  • You can only determine that there is no match after the for loop is finished, by which time it's already too late to add the selected attribute to the desired default option.

    To work around it you can use another loop beforehand to decide which option should be selected:

    {% set ns = namespace(selected="None") %}
    {% for t in tdata if t[0] == t1is %}
        {% set ns.selected = t1is %}
    {% endfor %}
    <select class="form-control" id="types" name="types" combojs="types">
        {% for t in tdata %}
        <option value="{{ t[0] }}" {% if t[0] == ns.selected %} selected {% endif %}>
            {{ t[0] }}
        </option>
        {% endfor %}
    </select>