简体   繁体   中英

How do I get HTML inside Spacebars {{if}} to change reactively with a Session variable?

In my Meteor project, I want a template section to be displayed according to a Session variable; however, the HTML inside the {{#if}} is not appearing reactively.
How do I get {{#if}}{{/if}} to change reactively with a session variable?

HTML:

<head>
  <title>testApp</title>
</head>
<body>
  {{> testTemplate}}
</body>

<template name="testTemplate">
  {{#if isDisplayed}}
    <div>It's working!</div>
  {{/if}}
  <button id="testButton">Toggle Display</button>
</template>

JavaScript:

Session.setDefault("displayVar", false);

Template.testTemplate.helpers({
    isDisplayed: Session.get("displayVar")
});

Template.testTemplate.events({
    "click #testButton": function () {
        if (Session.get("displayVar")) {
            Session.set("displayVar", false);
        } else {
            Session.set("displayVar", true);
        };
    }
});

Assigning a helper as a value:

isDisplayed : Session.get('displayVar')

Is the same as doing:

isDisplayed: false // or true, or whatever 'displayVar' is when run

To solve this simply use a function (here, an ES6 Arrow function since Meteor uses Babel):

isDisplayed: () => Session.get('displayVar')

Using a function makes sure that a Tracker computation is generated.

Your helper needs to return the value from an anonymous function:

Template.testTemplate.helpers({
  isDisplayed: function(){
    return Session.get("displayVar");
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM