如何在Meteor/handlebars中调试模板?

6
根据这篇博客文章,我应该注册一个助手来更好地调试handlebars模板,但它不起作用: < p >< code >ReferenceError: Handlebars未定义< /code > 那么,在Meteor/handlebars中如何使用< code >{{debug}}< /code >呢?
4个回答

15

这是我在自己的项目中用于调试的帮助函数:

Template.registerHelper("debug", function(optionalValue) { 
  console.log("Current Context");
  console.log("====================");
  console.log(this);

  if (optionalValue) {
    console.log("Value"); 
    console.log("===================="); 
    console.log(optionalValue); 
  } 
});

你可以使用{{debug}}在模板中调用它,并显示当前所在的上下文。更多信息请参见http://docs.meteor.com/#/full/template_registerhelper


优秀的代码片段,不过我认为Meteor推荐使用符号 Template.myTemplate.helpers - zVictor
是的,但我相信它只会在特定的模板中可用。 - Erlend V
是的。因为这个原因,我更喜欢使用你的答案,但我猜另一种符号才是“正确”的。 - zVictor

6
在 Meteor 0.4.0 中,您可以这样注册处理程序:
Template.myTemplate.helpers({
  helper: function () {
    // some code here
    console.log(arguments);
  }
});

不需要直接调用Handlebars。


4
请确保您在客户端(或共享)Meteor代码中注册您的助手。
Handlebars.registerHelper('helper', function() {
  // Do stuff
});

这个应该可以通过你的模板中的{{helper}}来调用。


2
为了完整起见:您也可以使用
Template.registerHelper('helper', helperFunc);

使用Handlebars.regsterHelper('h',f);的替代方案更好,因为如果您决定在将来的某个时候使用其他替代品(例如Spacebars,Meteor的真实名称)如Meteor Jade,那么您的应用程序不需要进行太多的重构。

这实际上是针对被接受的答案的评论。期待有一天能获得50点声望。


Meteor的api已经改变了,现在看起来应该像你所说的那样。 - zVictor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接