關于這個問題,我如何進一步深入嵌套陣列并應用一些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 片段:
{% 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 %}
uj5u.com熱心網友回復:
這是您要查找的內容:
{% 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 %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/468028.html
