流星 - 变量后重新加载模板部分

时间:2016-08-31 09:37:07

标签: meteor meteor-blaze

我希望在变量更改后刷新/重新加载模板的一部分,这样如果变量为true则显示内容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>

2 个答案:

答案 0 :(得分:2)

You need to create a reactive data source to get the template helper to re-run when the variable changes, as a normal variable won't let the helper know when it changes value. The simplest solution is to use 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();
  }
});

If you need to access the value somewhere outside this template, you can use Session as an alternative reactive data source.

答案 1 :(得分:1)

@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}}