I’m encountering an issue with an script where I want to set a variable with text, including leading and trailing spaces, and then pass this string to the text.set_value service while preserving all spaces. Here’s the code snippet:
I’ve tried several workarounds such as using the intend filter, replace filter, and more, but unfortunately, none of them have been successful. Whenever I output the Jinja variable or use a filter, it always returns the string without spaces.
Interestingly, this behavior only occurs within the context of an automation. When I replicate the same logic in the DevTools → Template Editor, it works as expected.
Your test results imply that the value of a script variable is subjected to a trim operation where leading/trailing whitespace is removed.
In the Template Editor, you’re defining a Jinja2 variable (used within a template) whereas in the automation you’re defining a script variable (used within the entire automation/script).
I suspect that the variable is being returned as a YAML scalar value, which is always trimmed, as indicated by the debugger (value without quotes). Unfortunately, a basic string {{value|string}} filter doesn’t resolve the problem.
I can reproduce the behavior independently of a service call within a “variables” block as well. I have summarized the problem and my attempted solutions in a copy-and-paste script here: