I could really use some guidance/documentation on multi-line Jinja2 templates in my configuration files. I want to have a binary_sensor that sends “on” or “off” depending on whether the current Harmony activity in use has the TV turned on (this uses the Harmony component and the configuration posted here.
Right now I have it all in one extended line and it looks like this:
tv_on:
friendly_name: Living Room TV On
entity_id: remote.living_room_harmony_hub
device_class: connectivity
value_template: '{% if is_state_attr("remote.living_room_harmony_hub", "current_activity", "Watch Apple TV") %}on{% elif is_state_attr("remote.living_room_harmony_hub", "current_activity", "Watch TiVo") %}on{% elif is_state_attr("remote.living_room_harmony_hub", "current_activity", "Watch a Movie") %}on{% elif is_state_attr("remote.living_room_harmony_hub", "current_activity", "Play Xbox One") %}on{% elif is_state_attr("remote.living_room_harmony_hub", "current_activity", "Listen to Music") %}off{% elif is_state_attr("remote.living_room_harmony_hub", "current_activity", "PowerOff") %}off{% else %}off{% endif %}'
Unfortunately this doesn’t work.
If I punch the template alone into the front end template tester, it seems to work fine. But the resulting binary_sensor is always off.
And how do I make this, for readability, into a multi-line template?
I see examples where some of them start with “value_template: >” and others with “value_template: >-”. What’s the difference? And in the ones starting “>-” I see entries in the template that start and end with “{%-” and “-%}” but not always. There must be a trick here I’m missing.
Any thoughts? Is there documentation for this somewhere I’m not seeing?
Hey, that’s a helpful site! I don’t know if that was around when I was asking my question originally last year.
To add to what @pnbruckner said, there were two things I didn’t understand at the time going on in my original template problem:
The multi-line yaml syntax with the folded block style (newlines replaced with spaces inside the block) and with the final newline also stripped off with a minus sign (i.e. “>-“).
The jinja2 template whitespace stripping operator, explained here, which is also a minus sign.
So there are two different things with similar but not identical functionality, and one in yaml and one in jinja2. This was not easy to figure out!
I guess since I did figure it out a while back and now I have explained it too, I should probably supplement the official docs. I’ll write something up.