Template binary_sensor

I have the following binary_sensor configured:

binary_sensor:
  - platform: template
    sensors:
      template_test_4:
        friendly_name: "Template Test 4"
        value_template: >-
          {% set alpha %}
            {{ false }}
          {% endset %}
          {% set beta %}
            {{ true }}
          {% endset %}
          {{ alpha and beta }}

Obviously, I expect the value of the sensor to be “off” since alpha is false, however the value in home assistant is “on”.

Does Home Assistant not deal with Block Assignments correctly? Or am I missing something?

edit: I am on 2020.12.1, using the official Home Assistant Core docker.

Try this

        value_template: >
          {% set alpha = false %}
          {% set beta = true %}
          {{ alpha and beta }}

Thanks for the reply. I expect that to work, but it doesn’t fit my use case. alpha is actually an if/elif/else structure returns a boolean.

{% set alpha = true if some_test else false %}

{% if x %}
  {% set alpha = 'x' %}
{% elif y %}
  {% set alpha = 'y' %}
{% else %}
  {% set alpha = 'z' %}
{% endif %}

Thanks guys! Since your examples avoid the Block Assignment structure, can I assume that Block Assignments are not allowed in Home Assistant templates?

I’ve never used it to be honest. What you have looks like it conforms so if it does not work the I’d say you’re right.

It works, but you’d have to convert alpha and beta to booleans and there is no bool filter. Block sets are always strings. This is why your result is always true/on. You’re essentially saying {{ if alpha has characters in it and beta has characters in it }}.

3 Likes

Got it… thank you kindly!

Ninja’d by petro but I’ll post my pretty screenshots anyway …

Block Assignments do work:

But not in the manner you were using them because, as petro explained, they’re strings (logically ANDing two strings doesn’t produce the result you want).

2 Likes

I’ll give you the solution for your effort. Thanks everyone!!

1 Like

Also, thanks for the reminder that the template editor exists. That’s much easier than modifying sensors and restarting home assistant to test!

Thank you but I think Petro’s response identified the root-cause first and explains why your template behaves the way it does. My post just supports his explanation. Anyway, ultimately it’s your call.

1 Like

I don’t care, you can have it :wink:

Well now I feel like we need some sort of gladiator competition to determine the winner. Dodgeball perhaps?