简体   繁体   English

自定义车把帮手

[英]Custom handlebars helper

I have function which return JSON: 我有返回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. HTML页面正在呈现,没有错误,但是我看不到URL,也没有任何警告消息。 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. 看起来,在您的车把帮助器函数中, context.length将返回undefined ,因此没有什么要提醒的。

You'd want your for loop to stop at the length of the keys within the items key. 您希望for循环停止在items键内的键长处。 A short way to write that would be Object.keys(context.items).length . 一种简短的编写方法是Object.keys(context.items).length Similarly, the keys you need to iterate over are in context.items : 同样,您需要迭代的键在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. 根据列出的Template.mainmenu.menuitem函数,您不需要自定义的Handlebars帮助器。 You can use the built-in #each helper like so: 您可以像这样使用内置的#each帮助器:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM