I’m trying to include a textfield in a blueprint that parses the input text to an array of days on which the blueprint should run.
The if loop in the below statement is throwing an error: Incorrect type: expected ‘array’
blueprint:
input:
schedule_days:
name: Run on these days
description: >
Days on which the automation will run.
Write days in short form (mon, tue, wed, thu, fri, sat, sun).
Seperate days by comma's or spaces.
selector:
text:
variables:
days: !input schedule_days
condition:
- condition: time
after: !input schedule_start
before: !input schedule_stop
weekday: >
{% if 'mon' in states(days) %}
- mon
{% endif %}
I’ve also tried it as follows, but the same error is thrown.
weekday: >
{% set day_array = namespace(daylist=[]) %}
{% if 'mon' in states(days) %}
{% set day_array.daylist = day_array.daylist + [mon] %}
{% endif %}
{{ day_array.daylist }}
You should consider using split() to convert the comma-separated string to a list.
You supply split() with the delimiter to use for splitting the string. For example, this will use a comma as the delimiter split(',') and this uses a comma followed by a space split(', ').
Copy-paste this into the Template Editor and experiment with it:
The challenge you will face is that you have offered the user a choice of delimeters (commas or spaces) and split() doesn’t support multiple choices. Faced with this situation, you will have to use replace to normalize the string (such as replace spaces with commas and the replace double commas with a single comma) before splitting it.
… and replace double spaces with single spaces before the other replaces.
User inputs is horrible, the more options you give them the more creative they will be.
To simplify things, I suggest restricting the delimiter to a space character. It’s the default delimiter used by split() and it ignores consecutive space characters.
I still find it weird that it’s possible to use templating with other variables and not here, but anyway.
i’ve given up on this and have created a Template Condition that gives a rather elegant solution to the problem.
It solves the issue of the different separators as well. users can now use practically any combination of punctuation marks and spaces to separate the short form days.
It’s also very easily copied over to other blueprints, so I’ve created another post for the script.