0

The following code selects all 3 of the options (though only perhaps one is 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 its size grows exponentially with the number of boolean tags. Is there a cleaner solution here? In the example below, pizza_dict is a python dict that associates each topping to the boolean value of whether it is on the 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>
Michael K
  • 2,196
  • 6
  • 34
  • 52

1 Answers1

1

Could you not simplify this to something like:

<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>
extols
  • 1,762
  • 14
  • 19
  • I had that, and then I had beautifulsoup prettify it and wrecked the tags. This is probably the right solution to the question I asked, though. – Michael K Apr 17 '15 at 16:47
  • {% for k in pizza_dict %} {% endfor %} is what beautiful soup does to that code. – Michael K Apr 17 '15 at 16:56