简体   繁体   中英

Custom handlebars helper

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 ?

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;
});

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>

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