Create an array in a Jinja2 template

I am creating a telegram bot integration and wanting to create an inline keyboard for each light within a group. I am struggling a little with the Jinja syntax required to make that happen. The closest I have is:

      inline_keyboard: >
        {%- for entity_id in states.group.lights.attributes.entity_id -%}
        {%- set parts = entity_id.split('.') %}
          {{ states[parts[0]][parts[1]].name }} {{ states(entity_id) }}:/light_toggle, 
        {% endfor -%}"

It looks like Jinja is formatting this into a single line string which forces all buttons onto the same row:

Ideally it will generate the required array syntax as documented here: https://www.home-assistant.io/components/telegram_bot

        inline_keyboard:
          - "Edit message:/edit_msg, Don't:/do_nothing"
          - "Remove this button:/remove button"

Is it possible to generate an array from a template?

Jinja templates will only ever return a single string.

You can return an array as a string, but the only way to do that in your circumstances is with a single attribute from the state object. You won’t be able to get both the state and the name.

{{ states | selectattr('entity_id', 'in', state_attr('group.lights','entity_id')) | map(attribute='name') | list }}

You could try a macro, but a macro only outputs a string as well. So you’d essentially output your list as a string from the macro. Then add a square bracket before and after.

Also, your template has an extra double quote at the end.


after reading the documentation, i notice that the yaml requires a list. There’s no way to convert template output into a list. So everything I’ve written here will have the correct look, but not work.

2 Likes

Thanks for the clear explanation, looks like I will be writing a fair few more automations.

Interestingly it doesn’t like you can pass an argument along with an inline keyboard anyway (- "Key:/button argument) which makes this idea a non start anyway.