Jinja2 templating boolean variables cleanly

╄→尐↘猪︶ㄣ 提交于 2019-12-13 03:59:50

问题


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>

回答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>


来源:https://stackoverflow.com/questions/29704737/jinja2-templating-boolean-variables-cleanly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!