I am trying to write a macro that appends a string within a FOR loop but the Jinja script is behaving unpredictably . Here is the simplified code:
{% set Text="Start, " %}
{% for i in range(3) %}
{% set Text = Text ~ "item {i}, " %}
{% endfor %}
{% set Text = Text ~ "End" %}
RESPOND TYPE=command MSG="{Text}"
It should return “Start, item 0, item 1, item 2, End” but it only returns “Start, End” so the expression in FOR loop is not executed properly. I know that the FOR loop is executing since other code within the loop is executed but not the combining of the strings. Any idea or solutions to this? Any help will be much appreciated.
Jinja has really weird variable scoping rules. What is happening is that a new variable called Text is being created inside the for loop, separate from the variable in the outer code. The variable in the inner loop is then removed when the for loop exits.
If you do a google search for Jinja Variable Scope, you’ll find all sorts of workarounds, none of them are pretty. I’ve run into the problem myself, but I don’t have a solution
Thank you for you input. I managed to come up with a solution but it is not pretty
{% set Text=[“Start”] %}
{% for i in range(3) %}
M117 “{ Text.append(“Item " ~ i) }”
{% endfor %}
M117 “{ Text.append(“End”) }”
{% set Text=Text|join(”, “) %}
RESPOND TYPE=command MSG=”{Text}"
M117
Ideally I would use the {% do %} expression but that requires adding extensions to Jinja which I found confusing. As a substitute I am using the M117 as a place holder for the append function. As I said not pretty but it works.
I got working with an array by looking at other Jinja macros.
So you can update a list but not a string
Again coding not the best but the hack works
{% set look_back_days=7 %}
{% set check_date_list=[‘created_date’,‘updated_date’ ] %}
{%- set where_array = -%}
{{ where_array.append(’ WHERE ‘) }}
{% for check_date in check_date_list %}
{% set where_line=check_date +’>CURRENT_DATE()- ’ + look_back_days|string + ‘\n’ %}
{{ where_array.append( where_line) }}
{% if not loop.last %}
{{ where_array.append( ’ AND ‘) }}
{% endif %}
{% endfor %}
{% set joined = where_array | join (’ ') %}