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

Highlighted
Occasional Contributor | Platinum Partner

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>

 

Reply
0 Upvotes
6 Replies 6
Highlighted
HubSpot Moderator

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.

Highlighted
Regular Advisor | Partner

My favorite parameter that I never get to use!

Highlighted
Community Manager

Hey @Amit_95 

 

Thank you for the information provided. I'll tag a few experts Smiley Happy

 

Hey @albertsg @amwilie @DanielSanchez do you have any thoughts you'd like to share with @Amit_95 

 

Thank you

Sharon


Did my post help answer your query? Help the Community by marking it as a solution
Highlighted
Advisor | Partner

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

Reply
0 Upvotes
Highlighted
Regular Contributor

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!

Highlighted
Regular Advisor | Partner

@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.

Stefen Phelps, Community Champion, Kelp Web Developer