How do I use If statement in GUI Helper Templates?

I have a helper that calculates the depth of oil in my tank. (Simply the air-gap from the tank sensor deducted from the tank height)

If HA is restarted and there is no value / unavailable for the tank air-gap sensor, then the calculation is incorrect and the value jumps up to the height of the tank.

Here is the code from the state template in the GUI:

{{ (states("input_number.oil_tank_height") | int(0) -states("sensor.oil_tank_gauge_depth") | int(0)) }}

How do I add a IF statement into this code in the GUI, to check that the sensor.oil_tank_gauge_depth is not unavailable before doing the calculation?

I tried following examples post on here, but they all seem aimed at YAML file configs, so the syntax is not quite right.

{% if has_value("sensor.oil_tank_gauge_depth") %}
  {{ states("input_number.oil_tank_height") | int(0) - states("sensor.oil_tank_gauge_depth") | int(0) }}
{% else %}
  this.state
{% endif %}

That should keep the last known good value.

Does your tank height really change?

Is there really a need to store it in an input number rather than just putting the number in the template?

1 Like

Thanks Tom.

I am still adjusting things at the moment, until I get all the values correct. Waiting delivery of oil at the moment, so will then know what ‘full’ shows from the sensor and can adjust things.