How to change a variable outside of a for loop? Scoping Issues

Highlighted
Regular Advisor | Gold Partner | HubSpot Certified Trainer

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 %}

@Anton@dennis_e@Stephanie-OG

1 Reply
Community Manager

Thanks for sharing @tjoyce!


Did my post help answer your query? Help the Community by marking it as a solution