Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a variable outside the scope of a Handlebars.js each loop

People also ask

How do you access variable outside loop?

SOLUTION: What you have to do to use a variable outside a loop, is to declare it before the loop begins, you don't have to initialize the variable before, but you have to initialize it before you try to use it for anything.

Can you use JavaScript in handlebars?

Handlebars doesn't allow you to write JavaScript directly within templates. Instead, it gives you helpers. These are JavaScript functions that you can call from your templates, and help you reuse code and create complex templates. To call a helper, just use it as an expression - {{helpername}} .

Does handlebars escape HTML?

HTML EscapingHandlebars will not escape a Handlebars.


Try

<option value="{{id}}">{{title}} {{../externalValue}}</option>

The ../ path segment references the parent template scope that should be what you want.


Or you can use absolute path like this:

<option value="{{id}}">{{title}} {{@root.user.path.to.externalValue}}</option>

I saw many links with 404 for documentation about this topic.

I update it with this one, it is working in April 1st 2020:

https://handlebarsjs.com/guide/expressions.html#path-expressions

Some helpers like #with and #each allow you to dive into nested objects. When you include ../ segments into your path, Handlebars will change back into the parent context.

    {{#each people}}
    {{../prefix}} {{firstname}} 
    {{/each}}

Even though the name is printed while in the context of a comment, it can still go back to the main context (the root-object) to retrieve the prefix.

WARNING

The exact value that ../ will resolve to varies based on the helper that is calling the block. Using ../ is only necessary when context changes. Children of helpers such as {{#each}} would require the use of ../ while children of helpers such as {{#if}} do not.

{{permalink}}
{{#each comments}}
  {{../permalink}}

  {{#if title}}
    {{../permalink}}
  {{/if}}
{{/each}}

In this example all of the above reference the same prefix value even though they are located within different blocks. This behavior is new as of Handlebars 4, the release notes discuss the prior behavior as well as the migration plan.