Explain Codes LogoExplain Codes Logo

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

javascript
handlebars
javascript-helpers
context-access
Nikita BarsukovbyNikita Barsukov·Jan 28, 2025
TLDR

To reference a variable from an outer scope in a Handlebars.js {{#each}} loop, use {{../yourVariable}}. This code hops up a layer to retrieve yourVariable from the surrounding context.

Usage:

{{#each array}} // Current loop item Inside loop: {{this}} // The escape artist also known as 'externalVar' Outside loop: {{../externalVar}} {{/each}}

Here, {{this}} represents the current element of the loop, while {{../externalVar}} fetches the externalVar from outside.

Root access in complex nesting situations

For nested loops, you might need to access a variable located multiple levels up. Easily reach the root level with {{@root.yourVariable}}.

Example:

{{#each topLevel}} {{#each secondLevel}} // "I'm the root variable, and I approve this message" Root variable: {{@root.externalVar}} {{/each}} {{/each}}

The snippet {{@root.externalVar}} accesses externalVar from the topmost context — no matter the nesting level.

Retaining context: refrain from arrow functions

Registering helpers? Use regular function expressions — not arrow functions — to preserve the intended this context.

Good:

Handlebars.registerHelper('myHelper', function() { // 'this' points to the expected context return this.externalVar; });

Bad:

Handlebars.registerHelper('myHelper', () => { // 'this' may not be what it seems it should be, trust issues arise return this.externalVar; });

Exploring nested objects with #each and #with

Handling nested objects? Use #each and #with helpers together to access your desired data.

Example:

{{#each person}} {{#with address}} // Using the parent context to send a postcard {{../personName}} lives in {{city}} {{/with}} {{/each}}

With {{../personName}}, you're stepping back into the parent context of the address object to grab personName.

Paths: tread with caution

Remember to carefully manage your paths when retrieving values. Ambiguous or incorrect paths can lead to unexpected outputs or errors.

Context shift: keep up or stay out

Sometimes, the context could change unexpectedly, especially after invoking certain helpers. If a variable becomes unreachable, review your context.

Consider This:

{{#let newContext=someValue}} // Expecting 'externalVar', but impostor 'newContext' showed up 🕵️‍♀️ {{../externalVar}} {{/let}}

Stay in the loop: syntax and usage

The significance of ../ has shifted in Handlebars version 4. Be sure to keep up with the official documentation for the most recent practices for accessing parent contexts.