简体   繁体   中英

handlebars.js helper doesnt work

I am somewhat losing my mind here... I have the following code:

<script id="myTemplate" type="text/x-handlebars-template"> 
  <div>{{post/name}}</div>
  {{#if post/attachments}}  
    <p>
    {{#list post/attachments}}<img src="{{url}}">{{/list}}  
    </p> 
  {{/if}}
</script>

And a helper which i copied directly from the each helper to make sure there were no errors.

Handlebars.registerHelper('list', function(context, fn, inverse) {
  var ret = "";

  if(context && context.length > 0) {
    for(var i=0, j=context.length; i<j; i++) {
      ret = ret + fn(context[i]);
    }
  } else {
    ret = inverse(this);
  }
  return ret;
});

window.myTemplate = Handlebars.compile($('#myTemplate').html());
window.myTemplate({post:{name:"Post!", attachments:[{url:"/images/preview.jpg"},{url:"/images/1.jpg"}]

This does not actually call the helper, code ends up looking like this:

<div></div>
<p>
  <img src>  
</p> 

Now I do this with an each block and it works fine, what am I missing?

Turns out I was including handlebars.js more than once on my page, which was causing my helpers to be ignored.

Now, if only I could find a way to get those hours of my life back...

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