【问题标题】:How can I put global template helpers together in Meteor?如何在 Meteor 中将全局模板助手放在一起?
【发布时间】:2018-01-20 13:37:18
【问题描述】:

我有几个全局模板助手

Template.registerHelper("termSuffix",function(){});

Template.registerHelper("subjects",function(){});

Template.registerHelper("date",function(){});
...

我试过这个(像普通/本地模板助手)

Template.registerHelper({
      termSuffix:function(){},
      subjects:function(){},
      date:function(){}
});

但它会抛出Exception from Tracker recompute function:Error: No such function: termSuffix

【问题讨论】:

  • 我不相信这是可能的。你有一个令人信服的理由想要这样做吗?如果它与非全局模板助手一致,那就太好了(r),但不支持这种语法(至少就文档而言)docs.meteor.com/v1.3.5/api/…
  • 我的应用里Template.registerHelper太多了,好像不太整齐。

标签: javascript meteor meteor-blaze spacebars meteor-helper


【解决方案1】:

全局帮助器不支持此语法。 DocsCode

如果您认为对库的更改足够引人注目,您可以提交拉取请求。

同时,您可以用自己的方法包装 Template.registerHelper 函数:

function registerGlobalHelpers(helpers){
    _.chain(helpers)
     .each( (fn, name) => { Template.registerHelper(name, fn); })
     .value();
  }

或在 underscorejs 中不带chaining 定义:

function registerGlobalHelpers(helpers){
  _.each(helpers, (fn, name) => { Template.registerHelper(name, fn); });
  }

然后像这样使用它:

registerGlobalHelpers({
      termSuffix:function(){},
      subjects:function(){},
      date:function(){}
})

【讨论】:

  • 简洁、简洁、优雅。谢谢@JeremyK +1
  • 这些命令大部分都是多余的,你可以使用_.each(helpers, (fn, name) => { Template.registerHelper(name, fn); });就足够了。
  • @Styx,是的,.key() 可以而且应该被删除,以便简化 iteratee 函数 - 我会更新这个。其余的是偏好问题。我喜欢链接命令的流畅界面方法,所以一般使用 .chain / .value 和下划线。不可否认,当他们之间只剩下一个赞扬时,是否增加了很多价值是值得商榷的!我会将这两个选项都添加到答案中
猜你喜欢
  • 2014-01-08
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 2015-01-06
  • 2014-07-23
  • 2014-04-04
相关资源
最近更新 更多