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

Jacob Lett is the founder of Bootstrap Creative, a digital marketing consultancy that helps Michigan manufacturers generate qualified leads through HubSpot, technical SEO, and Google Ads. With over a decade of hands-on experience, he acts as a direct partner for B2B companies seeking measurable ROI from their marketing investment.



Related posts

Tags: , ,

| Read My Editorial Policy

Want to Get Email Updates of New Articles?

Join My Email Newsletter