Jinja2 parses boolean variables carefully

The following code selects all 3 options (although desirable, perhaps one desirable).

<select id="example-getting-started" name="test" multiple="multiple">
    <option value="cheese" selected="NO">Cheese</option>
    <option value="tomatoes" selected>Tomatoes</option>
    <option value="mozarella" selected="maybe">Mozzarella</option>
    <option value="mushrooms">Mushrooms</option>
    <option value="pepperoni">Pepperoni</option>
    <option value="onions">Onions</option>
</select>

      

It's not hard to convert this to a Jinja2 template correctly, but it's verbose and grows in size exponentially with the number of boolean tags. Is there a cleaner solution here? In the example below pizza_dict

, this is a python dict that associates each vertex with a boolean value of whether it is on a pizza.

   <select id="example-getting-started" name="test" multiple="multiple">
       {% for k in pizza_dict %}
        {% if pizza_dict[k] %}
       <option value="{{ k }}">{{ k }}</option>
        {% else %}
       <option value="{{ k }}" selected>{{ k }}</option>
        {% endif %}
       {% endfor %}
    </select>

      

0


source to share


1 answer


Could you please simplify this:



<select id="example-getting-started" name="test" multiple="multiple">
   {% for k in pizza_dict %}
      <option value="{{ k }}" {% if pizza_dict[k] %}selected{% endif %}>{{ k }}</option>
   {% endfor %}
</select>

      

+1


source







All Articles