流星 - 变量更改后重新加载模板部分
Meteor - Reloading template section after variable change
我想在变量更改后 refresh/reload 我的模板的一部分,这样如果变量为真,它会显示内容 A,否则它会显示内容 B。我相信这是一个相当简单的问题,但我在寻找解决方案时遇到了麻烦。
像这样:
Template.x.created = function() {
this.variable = false;
}
Template.x.helpers({
'getValue': function(){
return this.variable;
}
});
模板:
<template name="x">
{{#if getValue}}
<content A>
{{else}}
<content B>
{{/if}}
</template>
您需要创建一个响应式数据源来让模板助手在变量更改时重新运行,因为普通变量不会让助手知道它何时更改值。最简单的解决方案是使用 ReactiveVar
:
Template.x.onCreated(function() {
this.variable = new ReactiveVar(false);
});
Template.x.helpers({
'getValue': function() {
// Note that 'this' inside a template helper may not refer to the template instance
return Template.instance().variable.get();
}
});
如果您需要访问此模板之外某处的值,您可以使用 Session
作为备用反应数据源。
@Waiski 的回答很好,但我想分享一个我构建的简单模板助手,因为很多模板都需要这个:
使用 registerHelper
你可以像这样构建一个全局助手:
Template.registerHelper('get', function (key) {
let obj = Template.instance()[key]
return (obj && obj.get) ? obj.get() : obj
})
在每个模板中使用它:
Template.x.onCreated(function() {
this.foo = new ReactiveVar(true)
this.bar = new ReactiveVar('abc')
})
Html:
{{#let foo=(get 'foo')}}
{{#if get 'bar'}}
Bar is true. Foo: {{foo}}
{{/if}}
{{/let}}
我想在变量更改后 refresh/reload 我的模板的一部分,这样如果变量为真,它会显示内容 A,否则它会显示内容 B。我相信这是一个相当简单的问题,但我在寻找解决方案时遇到了麻烦。
像这样:
Template.x.created = function() {
this.variable = false;
}
Template.x.helpers({
'getValue': function(){
return this.variable;
}
});
模板:
<template name="x">
{{#if getValue}}
<content A>
{{else}}
<content B>
{{/if}}
</template>
您需要创建一个响应式数据源来让模板助手在变量更改时重新运行,因为普通变量不会让助手知道它何时更改值。最简单的解决方案是使用 ReactiveVar
:
Template.x.onCreated(function() {
this.variable = new ReactiveVar(false);
});
Template.x.helpers({
'getValue': function() {
// Note that 'this' inside a template helper may not refer to the template instance
return Template.instance().variable.get();
}
});
如果您需要访问此模板之外某处的值,您可以使用 Session
作为备用反应数据源。
@Waiski 的回答很好,但我想分享一个我构建的简单模板助手,因为很多模板都需要这个:
使用 registerHelper
你可以像这样构建一个全局助手:
Template.registerHelper('get', function (key) {
let obj = Template.instance()[key]
return (obj && obj.get) ? obj.get() : obj
})
在每个模板中使用它:
Template.x.onCreated(function() {
this.foo = new ReactiveVar(true)
this.bar = new ReactiveVar('abc')
})
Html:
{{#let foo=(get 'foo')}}
{{#if get 'bar'}}
Bar is true. Foo: {{foo}}
{{/if}}
{{/let}}