我正在用 jinja2 做一个网络应用程序。我目前正在尝试使用数组中的元素配置 HTML select 元素。
数组中的每个元素都可以是字符串,或包含 2 个元素的数组:一个字符串和一个数字(这是标识符)。
我想根据元素的类型采取不同的行动。这是我试过的:
<select {{ "disabled" if Permission.WRITE not in field_permissions }} >
{% for e in field_data.enum %}
{% if e is iterable %}
<option value="{{ e[1] }}">{{ e[0] }}</option>
{% else %}
<option value="{{ loop.index - 1 }}">{{ e }}</option>
{% endif %}
{% endfor %}
</select>
但是“else”条件永远不会执行,因为字符串元素似乎被识别为可迭代元素,所以我的话被截断了:
你有解决方案来帮助我吗? :)
谢谢
请您参考如下方法:
你可以检查 e 是否是一个字符串:
<select {{ "disabled" if Permission.WRITE not in field_permissions }} >
{% for e in field_data.enum %}
{% if e is string %}
<option value="{{ loop.index - 1 }}">{{ e }}</option>
{% else %}
<option value="{{ e[1] }}">{{ e[0] }}</option>
{% endif %}
{% endfor %}
</select>
