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.