I have a timer, e.g. timer.rhs_garage_door_timer that should become Pieter's garage door. I can’t use '' (two single quotes) or \' since the former will result in a blank (as expected) and the latter is invalid (but I still tried, since Python works this way). What is the proper way to escape the apostrophe?
action:
- service: notify.mobile_app_xxx
data_template:
title: "Security"
message: "The {{ trigger.event.data.entity_id | replace('_timer', '') | replace('timer', '') | replace('_', ' ') | replace('.', '') | replace('rhs', 'Pieter's') }} has been left open for too long."
data:
push:
category: "cover_open"
Again answering my own question in a short period, but I figured it out and hopefully it will help others.
It essentially boils down to the different escaping rules, depending what you’re dealing with. In Jinja2, you escape a single quote by using another single quote. What I missed, was that the single quote I wanted to escape isn’t part of the template, but data inside the template, which requires YAML escaping. The right way to escape that is to use to backslashes (the backslash that escapes the single quote needs to be escaped too). The different behaviours are, of course, all well documented, but it wasn’t immediately obvious to me where the issue was.
message: "The {{ trigger.event.data.entity_id | replace('_timer', '') | replace('timer', '') | replace('_', ' ') | replace('.', '') | replace('rhs', 'Pieter\\'s') }} has been left open for too long."
Just to circle back to this once more, I think this is a much neater solution.
message: >-
{% set message_part = " has been left open for too long." %}
{% set name = None %}
{% if trigger.event.data.entity_id | regex_search("lhs", ignorecase=True) %}
{% set name = "Rouvé's garage door" %}
{% elif trigger.event.data.entity_id | regex_search("rhs", ignorecase=True) %}
{% set name = "Pieter's garage door" %}
{% else %}
{% set name = "The main gate" %}
{% endif %}
{{ name }}{{ message_part }}