Jinja模板如何实现字典列表渲染时除最后字段外其余末尾加逗号
问题原因
你之前代码中使用的loop.last是education_details数组遍历的循环变量,仅能判断当前是否为最后一条教育经历,无法判断单条教育经历内最后一个需要展示的非空字段,所以逻辑不符合需求。
正确实现方案
推荐先将单条教育经历中的非空有效字段存入临时列表,再通过遍历临时列表判断是否需要加逗号,Jinja原生的循环变量即可完美适配该场景,代码实现如下:
{% for data in profile.get('education_details', []) %} {# 收集当前教育经历的所有非空展示字段 #} {% set display_fields = [] %} {% if data.get('degree', '') %} {% set _ = display_fields.append(data.get('degree', '')) %} {% endif %} {% if data.get('type', '') %} {% set _ = display_fields.append(data.get('type', '')) %} {% endif %} {% if data.get('location', '') %} {% set _ = display_fields.append(data.get('location', '')) %} {% endif %} {# 渲染字段,仅在非最后一个字段后加逗号 #} {% for field in display_fields %} <span>{{ field }}</span>{% if not loop.last %}, {% endif %} {% endfor %} {% endfor %}
如果不需要给每个字段单独套<span>标签,还可以用join过滤器简化代码:
{% for data in profile.get('education_details', []) %} {% set display_fields = [] %} {% if data.get('degree', '') %} {% set _ = display_fields.append(data.get('degree', '')) %} {% endif %} {% if data.get('type', '') %} {% set _ = display_fields.append(data.get('type', '')) %} {% endif %} {% if data.get('location', '') %} {% set _ = display_fields.append(data.get('location', '')) %} {% endif %} <span>{{ display_fields | join(', ') }}</span> {% endfor %}
以上实现会自动适配字段为空的场景,不管单条教育经历有几个有效展示字段,都只会在字段之间添加逗号,最后一个字段末尾不会额外加逗号,完全匹配你给出的输出示例要求。
内容的提问来源于stack exchange,提问作者XD Sauaame
相关产品推荐
相关产品推荐

