This question is extremely common; How do I use a counter in a variable that was created outside of a for loop. @Jsum did a good job answering that question here. I just wanted to expand on it and make this post more “searchable” by users trying to accomplish the same thing.
{# create the counter #}{% set counter = {'value': 1} %}{# create a macro that will change the counter, when called #}
{% macro incrementDecrementCounter(valuechange) %}
{% set changingCounter = counter.update({'value': counter.value + valuechange}) %}
{% endmacro %}{# the for...loop #}
{% for n in range(10) %}
{% if n % 3 == 0 %} {# call the macro to update the counter #}
{{incrementDecrementCounter(-1)}}
{% else %} {# call the macro to update the counter #}
{{incrementDecrementCounter(1)}}
{% endif %}
<p>The loop index is: {{n}}, while the counter is: {{counter.value}}</p>
{% endfor %}
I didn’t think of using a macro, that’s a nice solution!
I found a hacky way to do something similar but different
This was some code I used to build a dictionary:
The ‘.append’ function actually appends to the global dictionary ‘vars’, the variable inside the set is irrelevant but is needed for the hubl to run
{% set vars = [] %}
{% for item in group %}
{% set thisVariableDoesntDoAnything = vars.append(item.variable) %}
{% endfor %}
I spent a whole day pulling my hair out until I came across this article. Maybe there are good reason to not allow outer variable to be set inside the for loop with a good old set statement. But it’s super counter intuitive (based on perhaps 99% of other languages out there). Big lame factor here imho.
Hi @darveesh and thank you for sharing your experience and feedback with the HubSpot Community!
I completely understand how frustrating it can be to run into unexpected scoping behavior, especially when it feels counter to conventions in other languages.
I’d recommend submitting this via the HubSpot Developer Feedback Form, then the right team can have their eyes on it.
We’re always working to improve, and your feedback about the developer experience is important.
Thank you again for being part of the HubSpot Community!
Have a great weekend!
Bérangère