Meteor 流星模板渲染两次
我的模板在第一次加载时呈现两次。我注意到这一点是因为Meteor 流星模板渲染两次,meteor,Meteor,我的模板在第一次加载时呈现两次。我注意到这一点是因为 Template.home.rendered = function() { console.log('rendered'); // => this is printed out twice console.log(Data.find({}).count()); // => this is initially 0, then 1 the second time } 此外,在第一次加载时,没有可用的数据。然而,在第二
Template.home.rendered = function() {
console.log('rendered'); // => this is printed out twice
console.log(Data.find({}).count()); // => this is initially 0, then 1 the second time
}
此外,在第一次加载时,没有可用的数据。然而,在第二次加载时,数据就在那里
是否有人知道这个问题可能是什么,以及为什么数据只在第二次出现?您需要找到一种方法,在数据可用时呈现模板
<template name="displayData">
<p>This is my data : {{this}}</p>
</template>
<template name="home">
{{#if myDataIsReady}}
{{#each data}}
{{> displayData}}
{{/each}}
{{/if}}
</template>
使用此模板结构,仅当myDataIsReady helper返回true时,才会呈现if块内容(恰好是显示数据的模板)。(因此仅触发渲染回调一次,数据立即可用)
但对于这样一个简单的任务来说,这是相当烦人的。
这就是为什么我建议使用铁路由器,这使事情更简单
使用“mrt Add iron router”将其添加到项目中,然后在client/router.js和client/router.html中使用以下样板代码:
Router.configure({
loadingTemplate:"loading"
});
Router.map(function(){
this.route("home",{
path:"/",
// we indicate which subscription has to be marked ready in order to load the template
waitOn:function(){
return Meteor.subscribe("myData");
}
// the result of this function will become our target template data context
data:function(){
return Data.find({});
}
});
});
<template name="home">
{{#each this}}
{{> displayData}}
{{/each}}
</template>
<template name="loading">
<p>Data isn't ready yet...</p>
</template>
Router.configure({
loadingTemplate:“正在加载”
});
Router.map(函数(){
这条路线(“家”{
路径:“/”,
//我们指出要加载模板,必须将哪个订阅标记为就绪
waitOn:function(){
返回Meteor.subscribe(“myData”);
}
//此函数的结果将成为我们的目标模板数据上下文
数据:函数(){
返回Data.find({});
}
});
});
{{{#每个这个}
{{>displayData}
{{/每个}}
数据还没有准备好
如您所见,Iron Router允许我们简单地指定我们在第一个代码示例中痛苦地手动实现的内容(等待特定订阅以呈现模板),当然,我们还可以获得免费路由、加载机制、布局管理等
在网上搜索完整的iron router教程(我的代码未经测试,但我希望它可以让你开始学习),它非常棒,最终会合并到Meteor中。我在/client
中有一个body.html,在/client/templates
中有一个appBody.html,在iron router中:
Router.configure({
layoutTemplate: 'appBody',
});
两个主体模板都已呈现(并且碰巧是相同的)。显然,需要删除
/client
中的body.html。这可能很有用:谢谢@go oleg。这看起来很有希望,但是我如何将其与模板的呈现
函数连接?我刚刚开始使用Meteor,所以这可能不是最好的方法…但是您可以创建一个isDataReady
模板帮助器,返回是否加载了数据
,并将{>home}
在{{{if isDataReady}}…{{/if}}
块中。感谢您的回答<代码>铁路由器听起来不错。然而,目前我使用的是流星路由器,它似乎没有这一功能。在铁路由器之前,基本上有两种路由解决方案,汤姆·科尔曼的流星路由器和克里斯·马瑟的迷你页面。他们最终合作开发了iron路由器,顾名思义,iron路由器是Meteor的可靠路由框架。强烈建议您花点时间重构应用程序以使用新路由器,因为它要好得多,而且以前的路由器可能不会得到维护,因为核心开发人员Tom Coleman正在开发iron-router。好的,谢谢您的解释。我一定会尽快做到的。
Router.configure({
layoutTemplate: 'appBody',
});