Handlebars.js使用../引用父上下文

问题描述 投票:22回答:1

假设我具有以下JSON和handlebars.js模板:

JSON

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

模板

<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>

上面的模板有效,直到我要过滤项目-假设有2个列出一个奇数,另一个列出偶数,这是一个简单的奇数模板:

<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>

和注册助手:

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

[辅助函数将按预期工作,并且仅渲染奇数项,但是对父上下文的引用丢失了,因此{{../rootPath}}指令~~未能渲染~~呈现空值。

是否可以通过块帮助器传递Parent上下文?

javascript templates handlebars.js mustache
1个回答
44
投票

更改此:

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

对此:

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

为什么?因为if语句在内部上下文中,所以首先您需要上一层,所以这就是为什么要添加../

查看更多详细信息,请参见:https://github.com/wycats/handlebars.js/issues/196

© www.soinside.com 2019 - 2024. All rights reserved.