I’m working on building some templates for my use. I have a lot of Jinja2 experience, so I thought I would share some with the community to use as a cookbook of sorts.
Here’s the first. This is a template that prints the name of all device_trackers that are marked at home and not_home with proper human string formatting.
{% for device in dict(states.device_tracker|groupby('state'))['home'] %}{% if loop.last and loop.length > 1 %} and {% elif not loop.first and loop.length > 1 %}, {% endif %}{{ device.name }}{% endfor %} {% if dict(states.device_tracker|groupby('state'))['home']|length == 1 %}is{% else %}are{% endif %} at home.
{% for device in dict(states.device_tracker|groupby('state'))['not_home'] %}{% if loop.last and loop.length > 1 %} and {% elif not loop.first and loop.length > 1 %}, {% endif %}{{ device.name }}{% endfor %} {% if dict(states.device_tracker|groupby('state'))['not_home']|length == 1 %}is{% else %}are{% endif %} away.
Example output:
Robbie is at home.
Katie is away.
Breaking this template up to be a bit more readable (note that by doing this you will get funky spacing in the output!):
# Loop over devices with a state of not_home
{% for device in dict(states.device_tracker|groupby('state'))['not_home'] %}
# If this not the last device add a comma. Otherwise, use the word "and". Don't do either if there's only 1 device
{% if loop.last and loop.length > 1 %} and {% elif not loop.first and loop.length > 1 %}, {% endif %}
# Print the device name
{{ device.name }}
{% endfor %} {% if dict(states.device_tracker|groupby('state'))['not_home']|length == 1 %}is{% else %}are{% endif %} away.
# The line above will output 'is' or 'are' depending on how many devices are in the list.