Templates - Looping a list with commas


I have the sonarr sensor setup and created a template sensor to read out the attributes of today’s schedule:


Jeopardy!: S2017E02
New Girl: S06E11
friendly_name: Sonarr Upcoming
icon: mdi:television
unit_of_measurement: Episodes

> - platform: template
> sensors:
> tv_schedule:
> value_template: >-
> {%- for attr in states.sensor.sonarr_upcoming.attributes -%}
> {%- if not attr==“friendly_name” and not attr==“icon” and not attr==“unit_of_measurement” -%}
> {{attr}}{% if not loop.last %}, {% endif %}
> {%- endif -%}
> {%- endfor -%}

Jeopardy!, New Girl,

Jeopardy!, New Girl

I feel I am close, but how do I not display a comma if this is the last entry?

Thank you!

Since you’re looping over the attributes, the last may be “unit_of_measurement” or something else… so you can’t use loop.last in that context. At least not when you’re filtering via attr.

You might be able to accumulate with a set {% set text = text + ", " + attr %}
and then afterwards, strip the extra comma and output it only on loop.last
I’m not sure how you’d remove that last character, tho.

Really, the right way is probably to accumulate a list, then use a join. Hope that pushes you toward a good option.

IIRC, Jinja scopes variables within for loops, so you can’t set it inside the loop and use it outside.

Check this out:

{%- for attr in states.sensor.sonarr_upcoming.attributes -%}
{%- if not attr=="friendly_name" and not attr=="icon" and not attr=="unit_of_measurement" and not attr=="hidden" %}
{%- endif -%}
{%- endfor -%}


The Good Doctor:S01E18