2
votes

I have function which return JSON:

  Template.mainmenu.menuitem = function() {
    var jsonObj = { items: [
        { url: "http://google.com", title: "google" },
        { url: "http://stackoverflow.com", title: "stackoverflow" },
      ] };

    return jsonObj;
  };

And I have custom handlebars helper:

  Handlebars.registerHelper('woodoo', function(context, options) {
    var ret = "";
    for(var i = 0, j = context.length; i < j; i++) {      
      ret = ret + options.fn(context[i]);
      alert(ret);
    }

    return ret;
  });

This is template:

<template name="mainmenu">
  {{#woodoo menuitem}}
    <a href="{{url}}">{{title}}</a>
  {{/woodoo}}

HTML page is rendering without error, but I can not see urls and I don't have any alert message. Why and how can I fix it ?

2

2 Answers

2
votes

It looks like, in your handlebars helper function, context.length would return undefined, so there would be nothing to alert.

You'd want your for loop to stop at the length of the keys within the items key. A short way to write that would be Object.keys(context.items).length. Similarly, the keys you need to iterate over are in context.items:

Handlebars.registerHelper('woodoo', function(context, options) {
  var ret = "";
  for(var i = 0, j = Object.keys(context.items).length; i < j; i++) {
    ret = ret + options.fn(context.items[i]);
  alert(ret);
}
  return ret;
});
1
votes

Given the Template.mainmenu.menuitem function you listed, you don't need a custom Handlebars helper. You can use the built-in #each helper like so:

<template name="mainmenu">
  {{#each menuitem.items}}
    <a href="{{url}}">{{title}}</a>
  {{/each}}
</template>