简体   繁体   中英

Handlebars.js using ../ to reference parent Context

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM