Meteor.js-在渲染的模板中调用模板助手 [英] Meteor.js - Calling a template helper within template rendered
问题描述
我正在使用Meteor 1.0.
I'm using Meteor 1.0.
我有一个Template.*name*.rendered
函数,可以进行许多计算.在计算结束时,我希望输出结果进入Template.*name*.helpers
,因此可以在相应的html页面中使用它.
I have a Template.*name*.rendered
function that makes a number of calculations. At the end of the calculations, I would like the output to make its way into a Template.*name*.helpers
so I can use it in the corresponding html page.
这是代码的简化版本:
Template.myTemplate.rendered = function () {
var x = Math.random();
Template.otherTemplate.helpers({
randomNum: x
});
}
当我在otherTemplate
中调用{{randomNum}}
时,什么也没有发生.
When I call {{randomNum}}
in otherTemplate
, nothing happens.
我也尝试将Template.*name*.helpers
放在Template.*name*.rendered
之外,在这种情况下,我得到了错误:
I have also tried putting the Template.*name*.helpers
outside of Template.*name*.rendered
, in which case, I get the error:
Uncaught ReferenceError: x is not defined
有想法吗?
推荐答案
这并不是真正正确的方法,因为Meteor的工作方式是在应用程序启动之前而不是在运行时编译模板.尽管可能会出现类似 的情况(例如,通过使用 Template.registerHelper ),最好在rendered
回调中将反应变量设置为特定值,并设置辅助函数以将其返回:
This isn't really the right way of going about things as the way Meteor works is by compiling templates before the application starts, rather than at run-time. Whilst something along these lines may be possible (for example by using Template.registerHelper), it would be much better to set a reactive variable to a specific value in the rendered
callback and have the helper set to return that instead:
Session.setDefault('randomNum', 0);
Template.myTemplate.rendered = function () {
Session.set('randomNum', Math.random());
}
Template.otherTemplate.helpers({
randomNum: Session.get('randomNum')
});
如果您想为randomNum
使用私有变量,请查看 ReactiveVar .它可以是任何反应性数据源,并且可以工作.
If you'd rather use a private variable for the randomNum
, have a look at ReactiveVar. It could be any reactive data source and it would work.
这篇关于Meteor.js-在渲染的模板中调用模板助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!