Lets say I have the following JSON and handlebars.js template :
{ 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>
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?
js and the <script> Element. An HTML <script> element with type value of text/x-handelbars-template can be used to contain Handlebars. js template text and expressions.
Here is a simple example that formats a phone number. So long as you register the helper before you call it you should be able to use {{formatPhoneNumber phoneNumber}} anywhere in your code. Handlebars. registerHelper("formatPhoneNumber", function(phoneNumber) { phoneNumber = phoneNumber.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With