YAML anchors within state

I’m trying top use yaml anchors for the first time, but I can’t get it to work. The snippets below are a much simplified example of what I’m trying to do (the real calculation is many lines and many more variables). Am I dong something wrong, or is this not possible with anchors?

- sensor:
    - name: one
      state: >- 
        {% set a = 1 %}
        {% set b = 2 %}
        <<: &calc
          {{ a + b }}
- sensor:
    - name: two
      state: >- 
        {% set a = 3 %}
        {% set b = 4 %}
        <<: *calc

You can’t use it on a part of YAML. It needs to be a full section/kry (i.e. state in this case). In other words, you’re not anchoring YAML there. See Thomas Lovén - YAML for Non-programmers.

For your use case, I’d recommend reusable Jinja templates: Templating - Home Assistant.

2 Likes

Also, consider this as a string:

      state: "{% set a = 1 %}{% set b = 2 %}{{ a + b }}"

Can you add an anchor inside a string? Ofc no.

If you look at it that way it is indeed obvious, and I kind of figured this was not possible. I was hoping the <<: would be a way to work around that, but I now realize it is part of the string.