Handlebars.js: Global context not available in a loop?

Created on 19 Feb 2012  ·  3Comments  ·  Source: handlebars-lang/handlebars.js

If I have the following context:

{{model: {username: 'sontek'}, timezones: ['a', 'b', 'c']} 

and I do:

{{#each timezones }}
     {{model.username}}
{{/each}}

model doesn't exist so I can't access the username.

Most helpful comment

It's in the docs under "Paths"

Nested handlebars paths can also include ../ segments, which evaluate their paths against a parent context.

<h1>Comments</h1>

<div id="comments">
  {{#each comments}}
  <h2><a href="/posts/{{../permalink}}#{{id}}">{{title}}</a></h2>
  <div>{{body}}</div>
  {{/each}}
</div>

Even though the link is printed while in the context of a comment, it can still go back to the main context (the post) to retrieve its permalink.
The ../ path segment references the parent template scope, not one level up in the context. This is because block helpers can invoke a block with any context, so the notion of "one level up" isn't particularly meaningful except as a reference to the parent template scope.

All 3 comments

I found I can use ../model.username but can't find docs on that, I just found it in some bug reports.... Is that documented somewhere?

It's in the docs under "Paths"

Nested handlebars paths can also include ../ segments, which evaluate their paths against a parent context.

<h1>Comments</h1>

<div id="comments">
  {{#each comments}}
  <h2><a href="/posts/{{../permalink}}#{{id}}">{{title}}</a></h2>
  <div>{{body}}</div>
  {{/each}}
</div>

Even though the link is printed while in the context of a comment, it can still go back to the main context (the post) to retrieve its permalink.
The ../ path segment references the parent template scope, not one level up in the context. This is because block helpers can invoke a block with any context, so the notion of "one level up" isn't particularly meaningful except as a reference to the parent template scope.

Many thanks @sontek and @spadgos

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DylanPiercey picture DylanPiercey  ·  7Comments

ShintaroOkuda picture ShintaroOkuda  ·  7Comments

amirzandi picture amirzandi  ·  7Comments

rhariraman picture rhariraman  ·  5Comments

snimavat picture snimavat  ·  5Comments