Templating questions I didn't know I had

I am going through some of my old code now that I supposedly know a lot more :thinking:

I have come across a lot of inconsistent coding on my part which is fine in that there is some flexibility in HA with variations allowed. But with templating especially I am finding I have some questions.

Firstly, there is a directive here https://www.home-assistant.io/docs/automation/templating/ that says:

  • “You must surround single-line templates with double quotes ( " ) or single quotes ( ' ).”

Is this strictly true (or just safest to always do this) because I have lots of templates that work like this:

      - service: switch.turn_off
        data_template:
          entity_id: switch.zone{{ zone }}_valve

At least they did work in the summer as most (all?) of these ‘wrong’ examples that I have seem to relate to the old stuff I wrote relating to garden irrigation which hasn’t been used for several months.


ALSO,

Are these both correct?

      - service: input_datetime.set_datetime
        entity_id: input_datetime.phantom_bedtime
        data_template:
          time: "23:{{ (range(0, 30)|random|int) }}:00"
      - service: input_datetime.set_datetime
        data_template:
          entity_id: input_datetime.phantom_bedtime
          time: "23:{{ (range(0, 30)|random|int) }}:00"

It should work fine. You’d run into problems if your template starts with a special character or number. The parser needs to understand what you are entering. If you using a { as the starting character, the parser assumes you are giving a JSON object. In this case, you need to use quotes to assert that it is a string. Same goes for starting with a number, the parser assumes it’s a number. But because you are starting letters, the parser knows you have a string and therefore the quotes can be omitted.

Yes. Although it’s my personal opinion that the safer method would be the entity_id inside data_template. I’ve had issues with the entity_id outside the data/data_template in some service calls. It may not actually matter now. I believe the issues I was having was around 2015/2016.

1 Like

Thanks, that is a really useful explanation. (As oppose to just some statement of how it should be done).