Yep. That is a YAML list, so…like most lists, you need to specify the index you want. Each group of things between the ‘-’ character is an element, so forecast[0] would be the first one, forecast[1] the seconds, etc.
If you want to look at multiple days, you’ll have to do some more magic.
The easiest is to just use that index for the day. So if you wanted tomorrow, you’d use forecast[1].
trigger:
platform: template
value_template: "{{ {{ 'rainy' in [forecast[0].condition, forecast[1].condition] }}"
(see **Note at the end of this post)
Finally, there are the magic jinja2 filter commands that are 100% voodoo magic and only took me an entire year to even begin to understand.
I truly don’t expect these to make sense to anyone just learning YAML/JINJA2, but here are some examples. My 2 favorite jinja2 filters are ‘selectattr’ and ‘map’.
{{ state_attr('weather.home', 'forecast')[:4] | selectattr('condition', 'eq', 'rainy') | list | count }}
That one takes the up to the first 4 elements ([:4]
) in the forecast list and uses the selectattr filter to basically “extract all entries from the list that match this condition”. In my example, the condition is “any condition that is equal to rainy”. This returns an ‘object’, so I use the | list
command to convert the object to a list, then | count
to count how many there are. Essentially, this will just count how many days are going to be rainy.
{{ state_attr('weather.home', 'forecast')[:4] | map(attribute='condition') | list}}
This one uses the ‘map’ filter to create a group of things from the forecast based on what I say. So, this will return a list of JUST the conditions. Again, I use ‘list’ to convert it to a list.
['sunny', 'sunny', 'partlycloudy', 'partlycloudy']
Putting it all together, we can create the following automation.
- alias: Gonna Rain
variables:
# Change this to the number of days in the future you want to look.
days: 4
trigger:
# See Note below for time trigger reason
platform: time
at: "05:00:00"
condition:
- "{{ 'rainy' in state_attr('weather.home', 'forecast')[:days] | map(attribute='condition') }}"
action:
- service: notify.notify
data:
title: "It's gonna rain"
message: "Forecast shows rain in the next {{days}} days"
**Note: I decided to run this at a certain time rather than triggering on the forecast. Reason is, you probably don’t want to do something EVERY SINGLE TIME the forecast gets updated. For example, if you send a notification if it’s going to rain, you’d get a notification every time it shows rain in the forecast, even if it updates only the current temperature.