Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars.js using ../ to reference parent Context

Tags:

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?

like image 364
hokapoka Avatar asked Nov 05 '12 10:11

hokapoka


People also ask

Can you use Handlebars in JavaScript?

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.

How do you call a function in Handlebars?

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.


1 Answers

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

like image 93
Francisco Goldenstein Avatar answered Oct 11 '22 20:10

Francisco Goldenstein