dynamic contact variables cause multiple loop passes

I noticed a bug while coding a custom email module that uses contact properties as follows:

{% set bag = [] %}

{% for i in range(0,2) %}

{% do bag.append('x') %}

{{ bag }}

{% endfor %}

This prints what you can expect:

[‘x’]

[‘x’,‘x’]

Now when you use a contact property in the loop this still works:

{% set bag = [] %}

{% for i in range(0,2) %}

{% do bag.append('x') %}
{{ contact['property_x'] }}
{{ bag }}

{% endfor %}

Now when you make the contact property dynamic, based on i for example (something unknown when parsing), you get a weird effect:

{% set bag = [] %}

{% for i in range(0,2) %}

{% do bag.append('x') %}
{% set property = 'property_x_' ~i %}
{{ contact[property] }}
{{ bag }}

{% endfor %}

The output becomes:

actual_contact_property

[‘x’,‘x’]

actual_contact_property

[‘x’,‘x’,‘x’]

It seems that in order to get to know which contact properties will need to be fetched, it already runs through the loop, appending ‘x’ each time. However, during that first passing, it is not printing anything. You can only notice the double pass based on the length of bag that is already non zero when you come in the loop for the first time and print something.

This seems a bug to me, because this should not happen. My loop should only be passed 2 times in this example and the length of bag should be 2 after the loop finishes.

Hi PDeT,

To address this issue, one possible solution would be to initialize the “bag” list after the dynamic contact property is fetched and printed, like so:

{% for i in range(0,2) %}
{% set property = 'property_x_' ~i %}
{{ contact[property] }}
{% set bag = [] %}
{% for j in range(0,i+1) %}
{% do bag.append('x') %}
{% endfor %}
{{ bag }}
{% endfor %}

Hi @TDwebdev , thx for the suggestion. I found a workaround myself as well, I just wanted to document it here in case anyone bumps into it and looses sleep over it as I did. It’s a bug, plain and simple.

If you add some print statements just before and in the loop, you’ll see that the prints are not printed more than expected, but the array is filled more than expected. It’s clear to me that the loop is traversed more often than one would expect (probably to detect which contact properties need to be available in the ‘official’ run through the loop) and has unwanted side effects. The parser should be fixed to avoid any side effect. I don’t know if there are better ways/channels to flag a bug like this.