在 jinja 中枚举满足特定条件的列表 - 除了最后打印的值外,每个项目之间用逗号分隔
Enumerate a list in jinja that satisfies a certain condition - with commas in between each item except for the last value printed
如何省略返回列表中最后一项的逗号仅,下面是我的代码。
{%- for entity_id in states.group.all_updater_entities.attributes.entity_id -%}
{%- if states(entity_id) == 'on' -%}
{%- if not loop.last -%}
{{ state_attr(entity_id, 'friendly_name') | replace ('Updater', '') }}{{', '}}
{%- else -%}
{{ state_attr(entity_id, 'friendly_name') | replace ('Updater', '') }}
{%- endif -%}
{%- endif -%}
{%- endfor -%} has updates available.
if not loop.last
条件不起作用,因为返回列表的最后一项可能不是 for 循环中组的列表项。在此先感谢您的帮助。
你像这样修改你的 j2(将条件 if 添加到循环 for):
{%- for entity_id in states.group.all_updater_entities.attributes.entity_id if states(entity_id) == 'on' -%}
{%- if not loop.last -%}
{{ state_attr(entity_id, 'friendly_name') | replace ('Updater', '') }}{{', '}}
{%- else -%}
{{ state_attr(entity_id, 'friendly_name') | replace ('Updater', '') }}
{%- endif -%}
{%- endfor -%} has updates available.
优点是特殊的循环变量会正确计数;因此不计算未迭代的实体。
如何省略返回列表中最后一项的逗号仅,下面是我的代码。
{%- for entity_id in states.group.all_updater_entities.attributes.entity_id -%}
{%- if states(entity_id) == 'on' -%}
{%- if not loop.last -%}
{{ state_attr(entity_id, 'friendly_name') | replace ('Updater', '') }}{{', '}}
{%- else -%}
{{ state_attr(entity_id, 'friendly_name') | replace ('Updater', '') }}
{%- endif -%}
{%- endif -%}
{%- endfor -%} has updates available.
if not loop.last
条件不起作用,因为返回列表的最后一项可能不是 for 循环中组的列表项。在此先感谢您的帮助。
你像这样修改你的 j2(将条件 if 添加到循环 for):
{%- for entity_id in states.group.all_updater_entities.attributes.entity_id if states(entity_id) == 'on' -%}
{%- if not loop.last -%}
{{ state_attr(entity_id, 'friendly_name') | replace ('Updater', '') }}{{', '}}
{%- else -%}
{{ state_attr(entity_id, 'friendly_name') | replace ('Updater', '') }}
{%- endif -%}
{%- endfor -%} has updates available.
优点是特殊的循环变量会正确计数;因此不计算未迭代的实体。