如何将 Jinja `length` 逻辑应用于嵌套 JSON 数组?
How to apply Jinja `length` logic to nested JSON array?
重复 ,如何进一步深入嵌套数组并应用一些 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 %}
这是您要查找的内容:
{% 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 %}
重复 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 %}
这是您要查找的内容:
{% 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 %}