Problem Templating If-Then for Binary Sensor

Hi all,

I am having an issue with templating and am looking to get some advice. Hopefully its something small that I have overlooked and any input would be appreciated.

I am looking to create a rest binary sensor for my doorbell to determine what a particular setting is set to and almost have it figured out. I am having issues with templating an if-then statement. My current configuration that I have confirmed as working is here:

binary_sensor:
  - platform: rest
    scan_interval: 10
    resource: Doorbell HTTP Address
    username: !secret
    password: !secret
    authentication: digest
    name: Doorbell Online
    device_class: problem
    value_template: "{{ value.split('=')[-1] }}"

With the value template configured this way the result is a string that is correctly either “true” or “false” depending on what the doorbell setting is currently set to. However, I need to invert this so that if the setting is set to “true” the output of the value template needs to be a string that says “false”. Here is my attempt at a configuration for that scenario:

binary_sensor:
  - platform: rest
    scan_interval: 10
    resource: Doorbell HTTP Address
    username: !secret
    password: !secret
    authentication: digest
    name: Doorbell Online
    device_class: problem
    value_template: >
      {% if value.split('=')[-1] == 'false' %}
        true
      {% else %}
        false
      {% endif %}

The output of this configuration is always “false” no matter what the setting I am monitoring is set to. I feel like this should be a pretty straight forward task, but I am pretty unfamiliar with templating (hoping to get better) and I just can’t figure this one out. I feel like it is something simple that I am overlooking. I would greatly appreciate any input. Thanks.

What’s the actual response i.e. 'value'?

My guess is that there’s an extra space, which the first attempt handles (there’s probably a trim function in the “does this look true or false” code), whereas the second one is stricter and fails.

value_template: "{{ not value.split('=')[-1]|bool(1) }}"

Awesome, this fixed it! Thanks for the help. Any chance you could explain the back half of that template (for my own learning). I assume the “not” at the beginning just inverts the result of the expression, but not sure what the “|bool(1)” does? Maybe converts the string into a boolean?

bool() is documented here: Templating - Home Assistant

So the not flips true and false, and the bool converts the response in a more “forgiving” manner than your equality test.

The (1) is a default value in case the response cannot be converted to true/false — which combined with the not turns the sensor off in that case.

Sounds good, appreciate it!