How to use attributes in template sensor

Hi,

I’m trying to make a custom sensor template that looks like a threshold with use of two attributes with valuies from input numbers. But somehow the sensor results in unavailable.

- template:  
   - sensor:
      - name: Sensor_Name
        unique_id: sensor_name
        state: >
          {% if states('sensor.somesensor')|float < states('this.attributes.min_value')|float  %}
            below
          {% elif states('sensor.somesensor')|float > states('this.attributes.max_value')|float %}
            above
          {% else %}
            within
          {% endif %}
        attributes:
          min_value: "{{ states('input_number._min_value') | float }}"
          max_value: "{{ states('input_number._max_value') | float }}"

How can I make this work?

The this variable already contains the state object of the sensor, so you cannot use the states() function on it… and, due to load order, you will likely need to set a default as well.

- template:  
   - sensor:
      - name: Sensor_Name
        unique_id: sensor_name
        state: >
          {% if states('sensor.somesensor') | float < this.attributes.min_value | default( ? ) %}
            below
          {% elif states('sensor.somesensor') | float > this.attributes.max_value  | default( ? ) %}
            above
          {% else %}
            within
          {% endif %}
        attributes:
          min_value: "{{ states('input_number._min_value') | float }}"
          max_value: "{{ states('input_number._max_value') | float }}"

I know this is just an example, but just in case… the object id of an entity (like your input numbers) shouldn’t start with a punctuation or number.

Hi Drew,

Thanks for your help.
Created a sensor to keep track of bitcoin going under or above a certain level:

- template:
  - sensor:
      - name: Bitcoin drempelwaarde
        unique_id: bitcoin_drempelwaarde
        state: >
          {% if states('sensor.cryptoinfo_crypto_bitcoin_eur') | float < this.attributes.min_value | default( 15001 ) %}
            onder drempelwaarde
          {% elif states('sensor.cryptoinfo_crypto_bitcoin_eur') | float > this.attributes.max_value  | default( 25001 ) %}
            boven drempelwaarde
          {% else %}
            binnen drempelwaarde
          {% endif %}
        attributes:
          min_value: "{{ states('input_number.btc_min_value') | float }}"
          max_value: "{{ states('input_number.btc_max_value') | float }}"
          cur_value: "{{ states('sensor.cryptoinfo_crypto_bitcoin_eur') | float }}"

Works great now!