Javascript Meteor:在子模板中使用变量
我正在使用模板级订阅,但在子模板中使用结果时遇到一些问题: 当我加载模板Javascript Meteor:在子模板中使用变量,javascript,meteor,Javascript,Meteor,我正在使用模板级订阅,但在子模板中使用结果时遇到一些问题: 当我加载模板example时,将显示模板exampleChild(仅将此作为一个基本示例-我知道这现在没有意义) 创建主模板时,完成订阅并将数据存储在助手中: 模板 <template name="example"> {{> Template.dynamic template=switch}} </template> <template name="exampleChild"> <
example
时,将显示模板exampleChild
(仅将此作为一个基本示例-我知道这现在没有意义)
创建主模板时,完成订阅并将数据存储在助手中:
模板
<template name="example">
{{> Template.dynamic template=switch}}
</template>
<template name="exampleChild">
<h1>{{result}}</h1>
</template>
事件
Template.example.onCreated(function() {
var instance = this;
instance.autorun(function () {
var subscription = instance.subscribe('posts');
});
instance.result = function() {
return Collection.findOne({ _id: Session.get('id') });
}
});
如果我将
{{result}}
放在示例
-模板中,那么一切都正常。但是我需要使用子模板中的变量。您可以将结果存储在会话变量中,然后将另一个帮助程序添加到等待会话变量的exampleChild
。是否尝试:
<template name="example">
{{#with result}}
{{> Template.dynamic template=switch}}
{{/with}}
</template>
<template name="exampleChild">
<h1>{{this}}</h1>
</template>
{{#结果}
{{>Template.dynamic Template=switch}
{{/与}}
{{this}}
进行此操作时,我更喜欢将数据上下文结果包装到对象中,以便在子对象上具有适当的内容,如:
Template.example.helpers({
switch: function() { return 'exampleChild'; },
data: function() { return {result: Template.instance().result()} },
});
<template name="example">
{{#with data}}
{{> Template.dynamic template=switch}}
{{/with}}
</template>
<template name="exampleChild">
<h1>{{result}}</h1>
</template>
Template.example.helpers({
开关:函数(){return'exampleChild';},
数据:函数(){return{result:Template.instance().result()}},
});
{{{有数据}
{{>Template.dynamic Template=switch}
{{/与}}
{{result}}
希望对您有所帮助您可以使子模板看起来不包含在父模板中,并且它们实际上是同级模板。请澄清他们是否有兄弟姐妹关系或父/子关系。这是一个孩子,只是使用Dynamic.template,目前它并不“常见”,可能会混淆@Eleant.Scripting
Template.example.helpers({
switch: function() { return 'exampleChild'; },
data: function() { return {result: Template.instance().result()} },
});
<template name="example">
{{#with data}}
{{> Template.dynamic template=switch}}
{{/with}}
</template>
<template name="exampleChild">
<h1>{{result}}</h1>
</template>