I’m using some trigger based templates that get REST data and process it into multiple attributes. Several use the same code blocks so I create variables to pre-process some of the REST output to reuse in different attributes. I thought all was well until I read this in the documentation
variables map (Optional)
Key-value pairs of variable definitions which can be referenced and used in the templates below (for trigger-based entities only). Trigger based template entities resolve variables between triggers and actions.
(I’ve extracted the key sentence).
My question is: if the data used by the variable comes from the REST action and it is resolved BEFORE the action, where is it getting its data from?
A short extract of my template:
- trigger:
- platform: state
entity_id: input_button.tideq
action:
- service: rest_command.tide_heights_q
response_variable: heightsq
- service: [there are several more]
- variables:
gradient: >
{%- if heightsq.status != 200 %} {#- start by getting the query height again, plus 10 mins later #}
{%- from 'tide_macros.jinja' import harmonic_height %}
{%- set height = harmonic_height(when,ts,hs)|float(0) if when<=ts|max and when>=ts|min else 'n/a' %}
{%- set height10 = harmonic_height(when+600,ts,hs)|float(0) if when<=ts|max and when>=ts|min else 'n/a' %}
{%- set gradient = ((height10-height)*6) %}
{%- else %}
{% set gradient = (30*(heightsq.content | selectattr('DateTime', 'ge', (as_datetime(state_attr('sensor.tidequerytiming','query'))+timedelta(minutes=2)).strftime('%Y-%m-%dT%H:%M:00Z')) | map(attribute='Height') | first | float(0) - heightsq.content | selectattr('DateTime', 'ge', as_datetime(state_attr('sensor.tidequerytiming','query')).strftime('%Y-%m-%dT%H:%M:00Z')) | map(attribute='Height') | first | float(0))) %}
{%- endif %}
{{ gradient }}
sensor:
- unique_id: tideq
name: tideq
state: "{{states('input_datetime.tidequery')}}"
attributes:
rate: >
{{ gradient|round(1) }}
flow: >
{%- set itis = iif(gradient < 0, "ebb", "flood") %}
{%- if gradient|abs < 0.2 %}
Slack
{%- elif gradient|abs > 2.0 %}
{{"V fast "+itis }}
{%- elif gradient|abs > 1.5 %}
{{"Fast "+itis }}
{%- elif gradient|abs < 0.5 %}
{{"Slow "+itis }}
{%- else %}
{{ (itis+"ing")|capitalize }}
{%- endif %}
It seems to be working, or at least it is returning credible results.