Using for loop variable (defined in template partial) outside for loop

I have created a template partial file where I’m defining all variables based on a for loop. I then want to reference a variable (that is defined in that file) in custom modules.

However, the for loop closes in the partial file, so when I reference a variable in the HTML of a custom module, it’ll be out of scope.

Is there any way to use for loop variables outside the loop?

Demo:

Here is my template partial file:

<!--
 templateType: "global_partial"
 isAvailableForNewContent: false
-->

{% set table = hubdb_table_rows(table_id_here) %}

{% for row in table %}
 {% set firstname = row.first_name %}
{% endfor %}

And here is how I’m calling the variable in my markup (and what I want to acheive):

<div class="hero">  {% include "/template_partial_file.html" %}
 <h1>{{ firstname }}</h1>
</div>

Hey @Amit_95,

When looking to retrieve variable outside in a template partial file, you may want to explore the option of using export_to_template_context.

My favorite parameter that I never get to use!

Hey @Amit_95

Thank you for the information provided. I’ll tag a few experts :slightly_smiling_face:

Hey @albertsg @alyssamwilie @DanielSanchez do you have any thoughts you’d like to share with @Amit_95

Thank you

Sharon

Hi @Amit_95
Without Loop, you can’t identify the index, there are many rows in your HubDB Table right?
May I ask you the scope the Uses, I can help with Alternative solutions.
Thanks!
Ajit

Hi @sharonlicari (thanks for the tag!) and @Amit_95, find below my thoughts about this.
As per Hubspot’s documentation, any variables defined within loops are limited to the scope of that loop and cannot be called from outside of the loop.

With that being said, I believe you should use a different approach to achieve your goal.

As @psdtohubspot said, could you please provide us with more infomation about what you want to achieve so we can help you finding alternative solutions?

Thank you and have a nice day!

@Amit_95 as long as you create the variable outside the loop, you can then update the variable value inside the loop. Then when you reference the variable again outside the loop it will have the updated value.

I’m having a working solution. Just try this may be it’ll fix your problem.

{% set var = [] %}

{% for item in module.list %}
{% do var.append(item.name) %}
{% endfor %}

{{ var[0] }}

Here in the above code, I first initialize a variable named var as array and inside the forloop I am appending the value to the array variable.

In your case please try this

<!--
 templateType: "global_partial"
 isAvailableForNewContent: false
-->

{% set table = hubdb_table_rows(table_id_here) %}
{% set firstname_array = [] %}
{% for row in table %}
 {% set firstname = row.first_name %}
 {% do firstname_array.append(firstname) %}
{% endfor %}
<div class="hero"> 
 {% include "/template_partial_file.html" %}
 <h1>{{ firstname_array[0] }}</h1>
</div>