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


Written by: Jake Lett
Jake Lett is a B2B marketing consultant with over 15 years of experience in the digital marketing industry. He specializes in SEO, HubSpot, and PPC campaign management. Jake has a proven track record of helping businesses increase their online visibility and drive more traffic, leads and sales. He is a Certified Google Ads Specialist and a Certified HubSpot Developer.

Related posts

Tags: , ,

Want to Get Email Updates of New Articles?

Join My Email Newsletter