Comments in templates?

I’m having a hard time finding info on this…hope someone knows.

I have some templates that get fairly complicated, I’d like to add some comments to make them more maintainable. It seems putting a #something on an intermediate line messes things up or processes it as strings, is there some trick to making templates work properly and having comments on lines in the middle of the template code?

For example, I’m looking at something I wrote a while ago…

          {% if ( states('sensor.downstairs_thermostat_air_temperature') | float(0) ) == 0 or ( states('sensor.downstairs_thermostat_humidity_filtered') | float(0) ) == 0 or ( states('sensor.basement_hall_humidity_filtered') | float(0) ) == 0 %}
            # This case is if the temp is invalid we can't do the computation
          {% else %}
            # Crap I forgot what this was, but it was important
            {% set t = states('sensor.downstairs_thermostat_air_temperature') | float(0) %}
            {% set rh = (states('sensor.downstairs_thermostat_humidity_filtered') | float(0) + states('sensor.basement_hall_humidity_filtered') | float(0))/2 %}
            {% set rh = (rh * 1.1) + 8 %}
            {% set hi = 0.5 * (t + 61.0 + ((t-68.0)*1.2) + (rh*0.094))  %}
            # Now print...maybe this was feels-like temperature idk
            {{ (hi) | round(2,default=0) }}
          {% endif %}

But it doesn’t work because those don’t actually seem to be processed as comments, but just text?

1 Like
{# this is a jinja comment #}

See: Template Designer Documentation — Jinja Documentation (3.1.x)


Oh very cool! I don’t think I’ve seen that website before, looks like it has a lot of stuff that might be useful for templates. Do you know does all that work or is Home Assistant just using a subset of it or what?

Yes it is a handy reference. I don’t think I’ve ever used something that wasn’t implemented. Also I think Home Assistant has some extras like |is_number, these are in the HA template documentation.

1 Like

Yeah, I’ve poked at some of the HA docs but didn’t realize there was a wider general “how to write this stuff”. I’d always been having to comb thru the forums for hints about like “how do I do X mathematical function” and whatnot with the syntax.