Splitting long templates

I’ve been struggling to find a way to split long templates to preserve readability and avoid long lines in Yaml. For example, I have this template sensor to count how many “actual lights” are on.

I’ve tried avoiding one-liners since they are not very readable:

value_template: "{{ states | selectattr('entity_id', 'in', state_attr('group.actual_lights', 'entity_id')) | selectattr('state', 'eq', 'on') | list | count }}"

However, now I am not sure what the best approach might be to split it. Like this?

value_template: >
  {{ states |
     selectattr('entity_id', 'in', state_attr('group.actual_lights',
                                              'entity_id')) |
     selectattr('state', 'eq', 'on') | list | count }}

Or perhaps like this?

value_template: >
  {{ states
     | selectattr('entity_id',
                  'in',
                   state_attr('group.actual_lights', 'entity_id'))
     | selectattr('state', 'eq', 'on')
     | list
     | count }}

I would appreciate if anyone can shed some guidance on how they approach such cases. Perhaps a Jinja style guide they follow or some tips. Thanks.

Or like this:

value_template: >
  {{ expand('group.actual_lights')
     | selectattr('state', 'eq', 'on')  | list | count }}

Where you split it into multiple lines is just personal preference. What makes a difference is leveraging the available filters and functions to minimize the template.

1 Like

Touché. Perhaps a better question I may ask is what are your preferences when splitting long templates? :sweat_smile:

I use the | as a line-break to keep the template visible without having to scroll horizontally (see my example above).

1 Like