Drew Noakes Drew Noakes - 6 months ago 14x
Javascript Question

Access properties of the parent with a Handlebars 'each' loop

Consider the following simplified data:

var viewData = {
itemSize: 20,
items: [
'Zimbabwe', 'dog', 'falafel'

And a Handlebars template:

{{#each items}}
<div style="font-size:{{itemSize}}px">{{this}}</div>

This won't work because within the
loop, the parent scope is not accessible -- at least not in any way that I've tried. I'm hoping that there's a way of doing this though!


It turns out that this is possible by prepending ../ to the property name:

{{#each items}}
    <div style="font-size:{{../itemSize}}px">{{this}}</div>

You can go up multiple levels via repeating the ../. For example, to go up two levels use ../../key.

For more information, see the Handlebars documentation on paths.