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

janus-reith picture janus-reith  路  3Comments

asgraf picture asgraf  路  5Comments

ShintaroOkuda picture ShintaroOkuda  路  7Comments

morgondag picture morgondag  路  5Comments

nknapp picture nknapp  路  3Comments