Jinja2模板循环未匹配项时输出空引号的问题解决咨询
问题描述
我有一个Jinja2模板,用于遍历字典查找component_class == BSW_PROJECT的项。部分项目的字典中不存在BSW_PROJECT(属于正常情况),此时模板运行后会输出空引号"",不符合预期。
原模板代码:
requires = ["{% for name, info in idat_data["components"].items() if info["component_class"] == "BSW_PROJECT" %}{{name | lower}}_template/{{idat_data["components"][name]["component_version"]}}{%endfor}" ]
当前生成的结果:
requires = [ "" ]
预期输出:
requires = [ ]
尝试过在for循环和endfor中添加%-和-%,但无法解决问题,请问如何阻止空引号的输出?
解决方案
方法1:先筛选匹配项再判断输出
先用selectattr筛选出符合component_class == "BSW_PROJECT"的组件,只有存在匹配项时才输出带引号的内容,空数组直接留空:
requires = [ {% set bsw_projects = idat_data["components"].items() | selectattr(1, "component_class", "BSW_PROJECT") %} {% if bsw_projects %} "{{ bsw_projects | map(attribute=0) | lower | map('format', '%s_template/' ~ idat_data["components"][item]["component_version"]) | join('", "') }}" {% endif %} ]
方法2:通过变量存储循环结果
把循环生成的内容先存入变量,处理掉多余的分隔符后,再判断是否输出引号:
{% set req_content = "" %} {% for name, info in idat_data["components"].items() if info["component_class"] == "BSW_PROJECT" %} {% set req_content = req_content ~ (name | lower) ~ "_template/" ~ info["component_version"] ~ '", "' %} {% endfor %} {% if req_content %} {% set req_content = req_content[:-4] %} {# 移除末尾多余的`", "` #} {% endif %} requires = [{% if req_content %} "{{ req_content }}" {% endif %}]
方法3:用列表收集结果再拼接
通过do语句把符合条件的项收集到列表中,再根据列表是否为空决定输出内容:
{% set req_items = [] %} {% for name, info in idat_data["components"].items() if info["component_class"] == "BSW_PROJECT" %} {% do req_items.append((name | lower) ~ "_template/" ~ info["component_version"]) %} {% endfor %} requires = [{% if req_items %} "{{ req_items | join('", "') }}" {% endif %}]
内容的提问来源于stack exchange,提问作者Twowolfs
相关产品推荐
相关产品推荐

