Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja 2 - Is variable string or array?

Tags:

python

jinja2

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

like image 365
graille Avatar asked Nov 25 '25 21:11

graille


1 Answers

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>
like image 156
olinox14 Avatar answered Nov 27 '25 10:11

olinox14



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!