I have 2 template binary_sensors defined in YAML (in a templates file ‘included’ in configuration.yaml). They are identical apart from 1 or maybe 2 variables (DEFANGLE and CLOUDY) that I set. I would like to create the code once and then re-use that YAML with differing values for 1 or 2 of those variables.
I’ve looked at ‘includes’ and ‘anchors’, but the former seems to not be usable in this case and the latter is not clear to me.
The following works as I want, but with much duplicated code and I’m a DRY lover so would like to coalesce the basic code into one ‘block’ and re-use that in the 2 sensors, but varying only by 1 or 2 variable values.
Currently I’ve been unable to figure out a solution to this, so am hoping someone more expert in YAML can offer some guidance.
- binary_sensor:
- name: "daylight"
unique_id: binary_sensor.daylights
variables:
# adjust these to suit
# default elevation to use
DEFANGLE: -2
# adjustment for cloudy conditions
CLOUDY: +4
# don't touch the rest
ELEV2USE: >
{% set WEATHER = states('weather.forecast_home') %}
{% if WEATHER in ['sunny','clear','clear-night'] %}
{{ DEFANGLE }}
{% elif WEATHER == 'partlycloudy' %}
{{ DEFANGLE + CLOUDY / 2 }}
{% else %}
{{ DEFANGLE + CLOUDY }}
{% endif %}
# get degrees as seconds @ 4 min/°
ELEVASECS: >
{{ ELEV2USE * 4 * 60 }}
NEXTDARK: >
{{ (states('sensor.sun_next_setting') | as_timestamp - ELEVASECS) | timestamp_custom("%H:%M", True) }}
NEXTLIGHT: >
{{ (states('sensor.sun_next_rising') | as_timestamp + ELEVASECS) | timestamp_custom("%H:%M", True) }}
state: >
{{ states.sun.sun.attributes.elevation > ELEV2USE }}
icon: >
{% if this.state == "on" %}
mdi:brightness-5
{% else %}
mdi:brightness-3
{% endif %}
attributes:
DEFANGLE: "{{ DEFANGLE }}"
ELEV2USE: "{{ ELEV2USE }}"
NEXTDARK: "{{ NEXTDARK }}"
NEXTLIGHT: "{{ NEXTLIGHT }}"
- name: "dayloght"
unique_id: binary_sensor.dayloghts
variables:
# adjust these to suit
# default elevation to use
DEFANGLE: -8
# adjustment for cloudy conditions
CLOUDY: +4
# don't touch the rest
ELEV2USE: >
{% set WEATHER = states('weather.forecast_home') %}
{% if WEATHER in ['sunny','clear','clear-night'] %}
{{ DEFANGLE }}
{% elif WEATHER == 'partlycloudy' %}
{{ DEFANGLE + CLOUDY / 2 }}
{% else %}
{{ DEFANGLE + CLOUDY }}
{% endif %}
# get degrees as seconds @ 4 min/°
ELEVASECS: >
{{ ELEV2USE * 4 * 60 }}
NEXTDARK: >
{{ (states('sensor.sun_next_setting') | as_timestamp - ELEVASECS) | timestamp_custom("%H:%M", True) }}
NEXTLIGHT: >
{{ (states('sensor.sun_next_rising') | as_timestamp + ELEVASECS) | timestamp_custom("%H:%M", True) }}
state: >
{{ states.sun.sun.attributes.elevation > ELEV2USE }}
icon: >
{% if this.state == "on" %}
mdi:brightness-5
{% else %}
mdi:brightness-3
{% endif %}
attributes:
DEFANGLE: "{{ DEFANGLE }}"
ELEV2USE: "{{ ELEV2USE }}"
NEXTDARK: "{{ NEXTDARK }}"
NEXTLIGHT: "{{ NEXTLIGHT }}"