Handlebars.js using ../ to reference parent Context

hokapoka picture hokapoka · Nov 5, 2012 · Viewed 20.7k times · Source

Lets say I have the following JSON and handlebars.js template :

JSON

{ 
  rootPath: '/some/path/',
  items:[ {
    title: 'Hello World',
    href: 'hello-world'
  },  {
    title: 'About',
    href: 'about'
  },  {
    title: 'Latest News',
    href: 'latest-news'
  }
}

Template

<script id="test-template" type="text/x-handlebars-template">

  <ul class="nav">
    {{#each items}}
      <li><a href="{{../rootPath}}{{href}}">{{title}}</a></li>
    {{/each}}
  </ul>

</script>

The template above works, until I want to filter items - lets say to have 2 lists one odd and the other even, here's a simple template for odd :

<script id="test-template" type="text/x-handlebars-template">

  <ul class="nav">
    {{#each items}}
      {{#isOdd @index}}
        <li><a href="{{../rootPath}}{{href}}">{{title}}</a></li>
      {{/isOdd}}
    {{/each}}
  </ul>

</script>

And the registered helper :

// isOdd, helper to identify Odd items
Handlebars.registerHelper('isOdd', function (rawValue, options) {
  if (+rawValue % 2) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});

The helpers work as expected and only the Odd items are rendered, however the reference to the parent context becomes lost, so the {{../rootPath}} directive ~~fails to render~~ renders an empty value.

Is there a way to pass the Parent context through the block Helper?

Answer

Francisco Goldenstein picture Francisco Goldenstein · Nov 5, 2012

Change this:

<a href="{{../rootPath}}{{href}}">

to this:

<a href="{{../../rootPath}}{{href}}">

Why? because the if statement is in an inner context so first you need to go up a level and that's why you have to add ../

See more details in: https://github.com/wycats/handlebars.js/issues/196