如何将Jinja '长度'逻辑应用于嵌套的JSON数组?



重复这个问题,我如何进一步钻入嵌套数组并应用一些length逻辑?

目标:如果PositionsHeld数组有多于1个条目,我想用逗号,分隔值,但最后一个条目不使用逗号分隔值.

例子:

JSON代码片段:

{
"Employers": [
{
"EmploymentType": "Food Service",
"Employer": "Test Brew",
"EmployerURL": "",
"StartMonth": 9,
"StartYear": 2020,
"EndMonth": null,
"EndYear": null,
"City": "Olympia",
"State": "WA",
"PositionsHeld": [
{"Position": "Barista"},
{"Position": "Asst. Manager"}
]
},
{
"EmploymentType": "Food Service",
"Employer": "The Steakhouse",
"EmployerURL": "https://www.steakmill.com/",
"StartMonth": 7,
"StartYear": 2019,
"EndMonth": 1,
"EndYear": 2020,
"City": "Milton",
"State": "WA",
"PositionsHeld": [
{"Position": "Busser"}
]
}
]
}

HTML w/Jinja snippet:

{% for e in data.Employers %}
<h3>
{% for p in e.PositionsHeld %} 
{% if p|length > 1 %}     <-- Here is the crux of question -->
{{ p.Position }} ,    <-- Want to add a "," if needed BUT NOT TO THE FINAL POSITION-->
else {{ p.Position }} 
{% endif %} 
{% endfor %}
</h3>
{% endfor %}

这就是你要找的东西:

{% for e in data.Employers %}
<h3>
{% for p in e.PositionsHeld %}
{% if not loop.last %}{{ p.Position }}, {% else %}{{ p.Position }}{% endif %}
{% endfor %}
</h3>
{% endfor %}

或者,更精简的版本(我更喜欢这种方式,因为它很简单):

{% for e in data.Employers %}
<h3>
{{ e.PositionsHeld | join(',', attribute="Position") }}
</h3>
{% endfor %}

最新更新