Display a {% for %} array as a linear-style sentence, one entity after the other in a single row?

This code displays a vertical list of entities meeting the filter conditions in a markdown card. How do I display this same list in a linear-style sentence? One entity after the other in a single row seperated by commas?

type: entity-filter
show_empty: false
entities:
  - group.attic_lights
  - group.basement_lights
  - group.bathroom_lights
state_filter:
  - 'on'
card:
  type: markdown
  content: >-
    {% for i in config.entities %}

      {{ i.entity }}

    {%- endfor %}

This is my first post. Thanks for your help.

Try this:

  content: >-
    {% for i in config.entities %}
    {{ i.entity }}
    {% endfor %}

It works because > means the YAML parser will merge your template into a single line like this:

  content: '{% for i in config.entities %} {{ i.entity }} {% endfor %}'

This, on the other hand, utilizes jinja2's whitespace control:

  content: |
    {% for i in config.entities -%}
    {{ i.entity + ' ' }}
    {%- endfor %}

Unfortunately, same result. But thank you.

After thinking about it, I feel like I need to build a new variable using the results of the current code. I’m just not that good at YAML. But someone more familiar who can see what I’m going for may be able to clean this up and finish my thoughts on this?

Something like?:

{% set var as string %}

{% for i in config.entities %}

  {% if i.entity <> null then var = var + i.entity %}

{% endfor %}

{{ var }}

That’s weird.
It worked when I tried it:

Another possible solution would be this:

{{ config.entities | map(attribute='entity') | join(', ') }}

EDIT:

Sorry, I didn’t notice this at first. I updated the template with join(', ') in this post.

1 Like

Thank you @ondras12345 !

It appears in the first example, the syntax for making the entire array in-line requires the dashes at the beginning and end of the ‘for’ loop.

i.e. -%} and {%-

Is that correct? Or just an anomaly in my experimentations?

In any event, both of your examples work! Have a merry Christmas. :wink:

That’s jinja2 whitespace control. I posted a link to the documentation in one of my previous posts.

:+1: thanks again!