![](/img/trans.png)
[英]How to use a jinja2 variable as an arg in a call to salt function inside a jinja2 statement
[英]How to use a variable inside of if statement in jinja2?
我從我迭代的Python應用程序收到一個列表( categories
)。 我想基於此列表中的輸入定義一個變量,將其與字符串合並,並將其用於進一步的循環。 串聯后, atom_type
的字符串文字將引用應用程序中的另一個列表。
{% for c in categories %}
{% set atom_type = 'atoms_' + c %}
{% for atom in atom_type %}
{% endfor %}
{% endfor %}
問題在於,在第二個for循環中, atom_type
被視為字符串,而不是對象。 如何使用atom_type
變量引用對象(Python列表)?
您可以將類別構建為字典列表,將其傳遞到模板並使用groupby()過濾器:
<ul>
{% for atoms in categories|groupby('atom_type') %}
<li>{{ group.grouper }}<ul>
{% for atom in group.list %}
<li>{{ atom.name }} {{ atom.weight }}</li>
{% endfor %}</ul></li>
{% endfor %}
</ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.