如何僅在回傳串列中的最后一項上省略逗號,這是我的代碼如下。
{%- 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 回圈中組的串列項。預先感謝您的幫助。
uj5u.com熱心網友回復:
你像這樣修改你的 j2(在回圈中添加條件 if):
{%- 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.
優點是特殊回圈變數會正確計數;因此不計算未迭代的物體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375308.html
