john
john

Reputation: 4158

jinja2 if statement not working

I have a jinja2 if statement where I am checking to see if the dictionary item is equal to an id however it never seems to evaluate it correctly or at all.

Here is my if statement:

<select id="deviceTypes" class="inputBoxes" style="height: 25px;">
    {% for key, value in deviceTypes.iteritems() %}
        {% if deviceTypeID == key %}  --> deviceTypeID is defined but this block of code never runs (key is an integer value, it's the id of the option)
            <option value="{{key}}" selected>{{deviceTypeID}}</option>
        {% else %}
            <option value="{{key}}">{{value}}</option>
        {% endif %}
    {% endfor %}
</select>

Upvotes: 0

Views: 5965

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124718

Most likely your deviceTypeID is taken from the request and still a string. Make sure it is an integer:

{% if deviceTypeID|int == key %}

or better still, turn it into an integer when you get it from the request. Many web frameworks let you turn a value into an integer when retrieving it; Flask lets you do:

deviceTypeID = request.form.get('deviceTypeID', type=int)

for example.

Upvotes: 2

user3716579
user3716579

Reputation: 11

Can you try to add 'not' to the check? This will tell you if the condition is false or not.

{% if not deviceTypeID == key %}

The answer:

{% if not deviceTypeID == key %}
    <option value="{{key}}">{{value}}</option>
{% else %}   
    <option value="{{key}}" selected>{{deviceTypeID}}</option>
{% endif %}

Upvotes: 1

Related Questions