流星有条件地显示嵌套模板
问题描述:
我有一个模板有几个子嵌套模板,应该有条件地显示基于保存在TemplateC集合中的数据,如下所示,所以我使用if条件在我的模板中,如下所示,但我总是即使条件返回true或false,也会显示所有子模板。有人可以检查我的代码,并告诉我我在这里失踪了什么?由于流星有条件地显示嵌套模板
var templateArray = ['false', 'false'];
Template.formBuilderPreview.created = function() {
var cursor = TemplatesC.find({}, { sort: { templateCode: 1 }});
if (!cursor.count()) return;
cursor.forEach(function (row) {
//only case 1 return in the switch below as case 2 never exist
switch(row.templateCode) {
case 1: templateArray[0] = true; break;
case 2: templateArray[1] = true; break;
default: templateArray[0] = true;
}
});
};
Template.formBuilderPreview.helpers({
template1box: function(){
console.log(templateArray[0]); //This returns true
return templateArray[0];
},
template2box: function(){
console.log(templateArray[1]); //This returns false
return templateArray[1];
}
});
模板:
<template name="formBuilderPreview">
<div id="fullpage">
{{#if template1box}}
{{> temp01}}
{{/if}}
{{#if template2box}}
{{> temp02}}
{{/if}}
</div>
</template>
答
你定义字符串数组,我相信这是造成麻烦,所以我建议你换
var templateArray = ['false', 'false'];
到
var templateArray = [false, false];
,它会工作顺利
答
把那个助手在一起。
Template.formBuilderPreview.helpers({
template1box: function(){
if(templateArray[1]){
return true;
}else{
return false;
}
});
现在模板应该看起来像这样。
<template name="formBuilderPreview">
{{#if template1box}}
<!-- If helper return TRUE this temp01 will be showed. -->
{{> temp01}}
{{else}}
<!-- If helper return FALSE this temp01 will be showed. -->
{{> temp02}}
{{/if}}
</template>
你得到帮助者的想法,使它只在1个帮手上,退出true/false
。
+0
感谢Ethaan为你的帮助,但如果我将有两个以上的子模板,这将是不实际的 – MChan 2015-04-01 22:24:30
非常感谢,它现在的作品! – MChan 2015-04-01 22:25:05