Trying to get rid of a few errors in the log - template sensor on an empty attribute

Hi All

I can see some errors for a few sensors that I extract attributes from, and just cleaning up a bit.
I’m using the meteoalarm, and I extract the color and type to seperate sensors to format the output a bit better.
The problem is that after a boot, the sensor doesn’t have all the attributes populated, so I will see errors like this:

Could not render template meteo_type, the state is unknown.

So I tried to change the template to this:

      meteo_type:
        value_template: '{% if states.binary_sensor.meteoalarm.attributes.event ==  "" %}off{% else %}{{ state_attr("binary_sensor.meteoalarm","event").split(" ")[1] }}{% endif %}'

I also tried

      meteo_type:
        value_template: '{% if states.binary_sensor.meteoalarm.attributes.event ==  none %}off{% else %}{{ state_attr("binary_sensor.meteoalarm","event").split(" ")[1] }}{% endif %}'

But I still get the error.
If I test the {{states.binary_sensor.meteoalarm.attributes.event}} it doesn’t show anything as it shouldn’t.

Try replacing:

states.binary_sensor.meteoalarm.attributes.event

with:

state_attr('binary_sensor.meteoalarm', 'event')

This should prevent errors when the attribute is unknown and is why you should always use this format for templates. There’s a yellow warning about it half way down this page:

1 Like

Hi @tom_l
Ok, at first I just had that in the config, and got the errors, then I ventured out into the jinja thing to get rid of the error :slight_smile:
If I just have this

      meteo_type:
        value_template: '{{ state_attr("binary_sensor.meteoalarm","event").split(" ")[1] }}'

I also get the error.
I think it’s because the ‘event’ attribute doesn’t exist at the time, even though the binary_sensor.meteoalarm does exist.

I have also tried:


`{{ is_state_attr("binary_sensor.meteoalarm","event", "") }}`

as a condition, but still get an error :slight_smile:

Try this:

      meteo_type:
        value_template: >
          {% set v = state_attr('binary_sensor.meteoalarm', 'event') %}
          {{ 'off' if v == none else v.split(" ")[1] }}

If the event attribute doesn’t exist, the state_attr function will return none. The second line will report off if the result is none otherwise it will process the result.

1 Like

@123 Ok, that is getting complicated :smiley:
But it works!
Thankyou to you both for suggestions!