lovelace-card-templater icon indicating copy to clipboard operation
lovelace-card-templater copied to clipboard

Using namespace doesn't seem to extend the scope beyond a single template

Open wigster opened this issue 3 years ago • 0 comments

Hi,

I am trying to achieve the following: I have two sets of sensors (weather from two locations, loc1=dejvice and loc2=podbaba). I usually prefer the loc1, but it is sometimes down (with a sensor-status != 'online'), so then I'd like to replace the sensors in a card with those from loc2 (or vice-versa).

The sensors are named wu_loc1_* and wu_loc2_*. I was hoping to set the string loc1 and loc2 using a template and then just use the template in the sensor names as I create the card.

As far as I can tell, I have to write an if/else logic for every entity in the card separately. HASS itself seems to support setting out-of-scope variables using Jinja2 namespaces, but I can't get it to work across entities.

Some code: The following works fine for the pressure sensor entity being defined right here. The sensor template is outside the if/else branch so namespace is working.

type: 'custom:card-templater'
entities: 
  - wu_dejvice_status
  - wu_podbaba_status
card:
      type: entities
      entities:
        - entity_template: >
            {% if states('sensor.wu_dejvice_status') == 'online' -%}
              {% if states('sensor.wu_podbaba_status') == 'online' -%}
                {% set ns = namespace(want_dej='dejvice',want_pod='podbaba') %}
              {%- else -%}
                {% set ns = namespace(want_dej='dejvice',want_pod='dejvice') %}
              {%- endif %}
            {%- else -%}
              {% if states('sensor.wu_podbaba_status') == 'online' -%}
                {% set ns = namespace(want_dej='podbaba',want_pod='podbaba') %}
              {%- else -%}
                {% set ns = namespace(want_dej='dejvice',want_pod='podbaba') %}
              {%- endif %}
            {%- endif %}  
            sensor.wu_{{ns.want_pod}}_pressure
          icon: 'mdi:arrow-collapse-down'

But if I try to refer to the ns variables in the next entity block, without repeating the if/then logic, it gives an error.

Is there a better way to achieve this? Or should I stop trying to be clever and just do a simple if/then for each sensor?

wigster avatar Mar 07 '21 11:03 wigster