Use templates to determine the attributes of a service call in a blueprint

I’m working on a new Blueprint that has a service call to turn on a light.
I’m trying to use a template to determine some attributes of this service call as per the documentation here:

Use templates to determine the attributes

Templates can also be used for the data that you pass to the service call.

You can use a template returning a native dictionary as well, which is useful if the attributes to be set depend on the situation.

service: climate.set_temperature
data: >
  {% if states('sensor.temperature_living') < 19 %}
    {"hvac_mode": "heat", "temperature": 19 }
  {% else %}
    {"hvac_mode": "auto" }
  {% endif %}

My code is as follows:

- service: light.turn_on
  data: >
    {% if include_color_or_temp == "include_color" %}
      {
        "transition": "!input transition_time",
        "rgb_color": "!input light_color"
      }
    {% elif include_color_or_temp == "include_temperature" %}
      { "transition": "transition_time_float", "temperature": "!input light_temp" }
    {% endif %}
  target: !input target_light

This gives the following error: expected float for dictionary value @ data[‘transition’]

transition_time is a number selector. I’ve already tried to change the code as follows:

variables:
  transition_time: !input transition_time
  transition_time_float: '{{ transition_time | float }}'

and then added it to the template as follows:

{% if include_color_or_temp == "include_color" %}
  {
    "transition": "transition_time_float",
    "rgb_color": "!input light_color"
  }

but the same error pops up.

If I remove the quotes around the transition_time_float variable or the !input transition_time variable , I get the following error: Error rendering data template: Result is not a Dictionary

I’m a bit at a loss here. Any help is greatly appreciated.

A few things to address…

  1. There shouldn’t be any !input tags inside your templates. These are YAML elements, the Jinja templating engine just sees them as strings.
  2. Any variables need to be left unquoted.
  3. The dictionary should be inside an expression so the variables can be rendered.
variables:
  transition_time: !input transition_time
  transition_time_float: '{{ transition_time | float(0) }}'
  color: !input light_color
  temperature: !input light_temp

....
action:
  - service: light.turn_on
    data: |-
      {% if include_color_or_temp == "include_color" %}
        {{ { "transition": transition_time_float, "rgb_color": color} }}
      {% elif include_color_or_temp == "include_temperature" %}
        {{ { "transition": transition_time_float, "temperature": temperature } }}
      {% endif %}
    target:
      entity_id: light.example
1 Like

Thanks so much, this works perfectly!

1 Like