[英]How do I change template helper function in Spacebars after template has been rendered?
[英]How to execute a function after a handlebars helper has been rendered
执行此Handlebars助手之后,如何每次都能获得一个要执行的函数?
Handlebars.registerHelper('renderPage', function() {
return new Handlebars.SafeString(Template[Session.get('currentPage')]());
});
这是在Meteor中运行的,我有一个在Session中设置新“ currentPage”的路由器,因为Session是反应性的,这将渲染我用“ currentpage”设置的模板。
我可以通过使用带有content元素的模板,然后使用Template.templateName.rendered来做到这一点,但这对我不起作用,因为我希望将此作为一个包,而现在我认为,您不能放置模板装入陨石包中。
如果是,我可以做:
Template.renderPage.content = function {
return new Handlebars.SafeString(Template[Session.get('currentPage')]());
});
Template.renderPage.rendered = function () { ... }
如果您希望函数在每次运行该助手时都运行,为什么不将其定义为助手的一部分呢?
Handlebars.registerHelper('renderPage', function() {
var ret = new Handlebars.SafeString(Template[Session.get('currentPage')]());
someFunctionYouWantToRun();
return ret;
});
更广泛地说,如果您希望函数和助手在每次页面更改时都运行,请创建一个包含其他模板的根级模板,然后将其附加到该页面的.rendered():
在index.html中 :
<body>
{{> root}}
</body>
在root.html中 :
<template name="root">
{{#if CurrentPageIsHome}}
{{> home}}
{{/if}}
</template>
在root.js中 :
Template.root.currentPageIsHome = function() {
return Session.equals("currentPage", "home");
}
Template.root.rendered = function() {
// Code you want run on every template render of root and every subtemplate
}
更好的是,使用Meteor Router包。
因此,对我来说有效的是使用模板而不是帮助器。 为了使该模板在陨石包中工作,我必须将它们包装在Meteor.startup函数中,否则将无法对模板进行优化。
Template.renderPage.content = function {
return new Handlebars.SafeString(Template[Session.get('currentPage')]());
});
Template.renderPage.rendered = function () { ... }
然后,我将Template.xxx.rendered函数用于事后挂钩。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.