Set Variable Values in a Loop and Use Elsewhere HubL HubSpot


Set Variable Values in a Loop and Use Elsewhere HubL HubSpot

When customizing a custom HubSpot quote template you may want to know what line items are present in the quote. You can then create conditional logic with a set of known values. The only problem is when you set a variable inside a loop it is not able to be referenced outside of the loop due to scoping rules. Below is some code you can use to get around this issue. Instead of setting a vanilla variable you are creating a dictionary outside of the loop with defaults and thin in the loop overriding these defaults. Since it is a dictionary, the code is easier to read later on because you are referencing the key in your variable declaration.

In my example below, I also wanted to include the number of line items in the list using loop.length.

{# does a freight line item exist? #}
  {% set line_item_conditions = {'freight_exists': False, 'wire_exists': False, 'loop_length': null  } %}
      {% for unit in LINE_ITEMS %}
         {% if unit.name == "Freight" %}
           {% do line_item_conditions.update({'freight_exists': True }) %}
          {% elif "Wire" in unit.name %}
            {% do line_item_conditions.update({'wire_exists': True }) %}
          {% endif %}  
          {% do line_item_conditions.update({'loop_length': loop.length }) %}
      {% endfor %}   


{% if line_item_conditions.loop_length >= 2 and line_item_conditions.freight_exists  %}
do your thing based on your list of conditions
{% endif %}  

About the Author

Jake Lett is a results-driven Detroit based B2B marketing consultant with 15+ years of hands-on experience managing SEO and PPC campaigns across manufacturing, SaaS, and professional services industries. He’s a Certified Google Ads Specialist and HubSpot CMS Developer who has personally managed budgets ranging from $500 to over $10,000/month.

Jake specializes in helping small businesses and solo marketers get more from lean ad budgets—using practical strategies that drive qualified leads, not just traffic. He shares real-world lessons on his blog, YouTube channel, and in his published books on digital marketing.



Related posts

Tags: , ,

Want to Get Email Updates of New Articles?

Join My Email Newsletter