Access a variable outside the scope of a Handlebars.js each loop
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:
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:
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:
Bad:
Exploring nested objects with #each and #with
Handling nested objects? Use #each
and #with
helpers together to access your desired data.
Example:
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:
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.
Was this article helpful?