Template not working and I don't see what's wrong

I have multiple cameras named cam1, cam2 etc. and for each camera I have a switch called switch.CAMERA_NAME_recordings. A variable named camera stores the name of the camera (cam1, cam2 …). I’m trying to use a template to replace a longer if then else block:

So, replace this

  variables:
    camera: "{{ trigger.payload_json['camera'] }}"

                  {% if camera == 'cam1' %}
                    {% if is_state('switch.cam1_recordings','off') %}
                      ...
                    {% else %}                  
                      ...                
                    {% endif %}
                  {% elif camera == 'cam2' %}
                    {% if is_state('switch.cam2_recordings','off') %}
                      ...
                    {% else %}                  
                      ...                
                    {% endif %}

with this:

                {% if is_state('switch.{{camera}}_recordings','off') %}
                  ...
                {% else %}                  
                  ...                
                {% endif %}

But this does not work.

Don’t nest templates like {{ ... {{var}} }}, just use the variable as-is {{ ..... var }}.

In your case you will need to concatenate the three parts to “build” the entity ID string:

{% set switch = 'switch.'~camera~'_recordings' %}
{% if is_state(switch, 'off') %}
...
{% else %}                  
...                
{% endif %}
1 Like

Cool. Thank you very much!