Losing variable when entering {{#each}} loop

Hi there,
I am building a select input in a form. Each option of the select input comes from an array pageData.assetTypes, and I have a default value stored as a string in pageData.type.

If my default value exists, I want it to be selected by default in my select input. I have done the following:

{{#if pageData.type}}
  {{#each pageData.assetTypes}}
    {{#eq pageData.type this}}
      <option value="{{this}}" selected>{{this}}</option>
    {{else}}
      <option value="{{this}}">{{this}}</option>
    {{/eq}}
  {/each}}
{{else}}
  <option value="" selected disabled hidden>Choose here</option>
  {{#each pageData.assetTypes}}
    <option value="{{this}}">{{this}}</option>
  {{/each}}
{{/if}}

I’m loosing the pageData.type value when entering the {{#each}} loop. Am I doing something wrong?
Cheers
Jules

When you’re inside an {{#each}} the context is entirely replaced with the object for the current iteration. If you want to access the root context, you can use @root. So you’ll need to use:

{{#eq @root.pageData.type}}

@root and other special variables are described here:

https://handlebarsjs.com/api-reference/data-variables.html#root

We also have an excellent Deeper Dive Webinar on Advanced Templating that covers this concept and many others here:

1 Like

Thanks @Brandon_Cannaday, I knew I should have dig deeper into the documentation.
It works fine now.
I’ll put this webinar on my to watch later list.
Cheers
Jules