Set Variable Values in a Loop and Use Elsewhere HubL HubSpot

Get FREE HubSpot Tutorial for Beginners PDF
Set Variable Values in a Loop and Use Elsewhere HubL HubSpot

When customizing a custom 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 == "Freight" %}
           {% do line_item_conditions.update({'freight_exists': True }) %}
          {% elif "Wire" in %}
            {% 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
I share digital marketing tips and HubSpot tutorials to help marketers and business owners grow their business.

Related posts

Tags: , ,

Want to Get Email Updates of New Articles?

Join My Email Newsletter