Question about hyphens in templates

Perhaps it’s me being thick (which I’ll happily accept :laughing: ), but could somebody ELI5 what the purpose is of the hyphen at various points in a jinja2 template please?

Firstly, lots of people have

value_template: >-

in their configs, but I never put the hyphen in and it works fine.

And then I’ve seen all variations of:

{%- if x == y -%} #hyphens at both ends
{%- elif g == h %} #hyphen only at the start

and various others, and none of it seems to make a bit of difference.

{% if x == y %}

Works fine.

I’ve looked at the jinja2 page, and tbh it was a bit overwhelming and I didn’t really understand it. It was talking about striping out whitespace, so you would think it would be fairly important in our yaml files. In the example on the page it suggest that it would be the difference between a template rendering:

value_template: 176

or

value_template:


                                                                  176

The latter obviously wouldn’t work if I manually typed it, but my templates all work fine without the hyphens.

So, satisfy an old man’s curiosity, what are they for?

Is it that homeassistant is clever enough to remove the whitespace from a templated entry anyway, so they’re redundant, but people use them out of good practice, or am I just fluking my way through life?

Thanks.

2 Likes

They trim out whitespaces.

http://jinja.pocoo.org/docs/2.10/templates/#whitespace-control

Yeah, thanks for the input, but that doesn’t help one little bit. :laughing:

As I’ve already explained I looked at that page and it makes no sense to me, and leaving them out in the homeassistant configuration files makes no difference as per the examples I gave in my post.

I would like a more ELI5 explanation please, and a simple answer to the question are they redundant in HA config?

Sorry, I’m not familiar with ELI5, and it’s not clear what you don’t understand. If it starts with {%-, that removes whitespaces at the beginning and if it ends with -%}, it removes whitespaces at the end. If you don’t include the -, whitespace is not trimmed.

ELI5 means Explain it like I’m 5.

So, if I’m not trimming the whitespace (which I’m not) how come when homeassistant resolves the templates I don’t get errors?

Sometimes you need to trim whitespaces for cosmetic reasons such as formatting text that will be sent via notifications.

1 Like