Jinja2干净地模板布尔变量 [英] Jinja2 templating boolean variables cleanly
本文介绍了Jinja2干净地模板布尔变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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>
将Jinja2模板正确转换为Jinja2模板并不难,但它很冗长,并且其大小呈指数级增长与布尔标签的数量。这里有更清洁的解决方案吗?在下面的例子中, pizza_dict
是一个python dict,它将每个顶点关联到它是否在披萨上的布尔值。
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>
推荐答案
p>
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>
这篇关于Jinja2干净地模板布尔变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文