graille
graille

Reputation: 1231

Jinja 2 - Is variable string or array?

I'm doing a web app with jinja2. And I am currently trying to configure an HTML select element with elements inside an array.

Each element inside the array can be a string, or an array containing 2 elements: a string and a number (which is the identifier).

I would like to act differently depending on the type of element. This is what I tried :

    <select {{ "disabled" if Permission.WRITE not in field_permissions }} >
        {% for e in field_data.enum %}
            {% if e is iterable %}
                <option value="{{ e[1] }}">{{ e[0] }}</option>
            {% else %}
                <option value="{{ loop.index - 1 }}">{{ e }}</option>
            {% endif %}
        {% endfor %}
    </select>

But the "else" condition is never executed because string elements seem to be identified as iterable elements, so my words are truncated :

Select buggued

Do you have a solution to help me with that? :)

Thanks

Upvotes: 3

Views: 4185

Answers (1)

olinox14
olinox14

Reputation: 6663

You could just check if e is a string:

<select {{ "disabled" if Permission.WRITE not in field_permissions }} >
    {% for e in field_data.enum %}
        {% if e is string %}
            <option value="{{ loop.index - 1 }}">{{ e }}</option>
        {% else %}
            <option value="{{ e[1] }}">{{ e[0] }}</option>
        {% endif %}
    {% endfor %}
</select>

Upvotes: 2

Related Questions