Can't get template to work, what am I missing?

Trying to learn how to use templates, so far it’s been a struggle and I can’t get the below to work.
What I want is to create a binary sensor that is based on mobile being connected to WiFi.
Created a templates.yaml file with the following code:

- binary_sensor:
    - name: niklas_connected_nikler
      device_class: "presence"
      state: >
        {% if is_state('sensor.dn2103_wifi_connection', 'NIKLER') %}
        {% set niklas_connected_nikler = 'home' %}
        {%else %}
        {% set niklas_connected_nikler = 'not_home' %}
        {% endif %}

The entity always show up as Away but when I test it in the templates editor in Developer tools like this it shows niklas_connected_nikler as home or not_home correctly:

- binary_sensor:
    - name: niklas_connected_nikler
      device_class: "presence"
      state: >
        {% if is_state('sensor.dn2103_wifi_connection', 'NIKLER') %}
        {% set niklas_connected_nikler = 'home' %}
        {%else %}
        {% set niklas_connected_nikler = 'not_home' %}
        {% endif %}

{{niklas_connected_nikler}}    

The sensor sensor.dn2103_wifi_connection comes from the Companion app in the mobile phone.

Can anyone please help?

Two issues:

  • Binary sensors expect their template to resolve to specific key words… The sensor is on if the template evaluates as True, yes, on, enable or a positive number. Any other value will render it as off.
  • Compared to what you were testing in the Template editor, your configuration is missing the expression that “prints” the value, i.e. {{niklas_connected_nikler}}. Without an expression all the sensor configuration “sees” is nothing… and nothing isn’t one of the key words.

However, all of that is really an over complication… all you need is:

- binary_sensor:
    - name: niklas_connected_nikler
      device_class: "presence"
      state: >
        {{ is_state('sensor.dn2103_wifi_connection', 'NIKLER') }}

Thank you so much!
That worked perfectly, and also added a bit of knowledge for future template creations!

Hi again, actually have a follow up question if you have the time…?
Can I create a device tracker out of this template?
Trying to get a more stable People home detection, would like to add this as an additional device-tracker under my People profile and ‘devices to track’.
Is that doable?

Yes, there are at least 2 ways that I know of.

  1. Install the Composite Tracker custom integration which accepts binary sensors and creates a device tracker entity.
  2. Use the state of your binary sensor as the trigger in an automation to call the device_tracker.see service.

Great, I’ll look into them.
Big thank you again!