Search code examples
meteormeteor-helper

How do I do an analog of a page scope in variable in Meteor?


I have this Meteor layout:

<template name="layout">
    {{> toolbar }}

    <div class="container">
        {{> yield}}
    </div>

</template>




Router.configure({
  layoutTemplate: 'layout'
});

I want to have the toolbar argument display dynamic content based on the page. I could do that by using some reactive variables. However, what happens when more than one page is open by the same client simultaneously? Every page's toolbar should display its own content, independent of each other. How do I implement it?


Solution

  • If you plan to use reactive data among several templates in the same page, I advise you to declare a reactive variable (ReactiveVar()) or a reactive dictionary

    At the beginning of your js file (if you have several, use the parent template file), outside any template.yourTemplate.rendered or template.yourTemplate.rendered, you declare it. The scope will cover all the templates called within the page.

    An example with reactive dict:

    var pageSession = new ReactiveDict();
    

    On your main template rendered function, you set your reactive variable:

    pageSession.set("yourVariable", yourValue);
    

    And you set an helper to return it:

    Template.layout.helpers({
        toolbar: function(){
            return pageSession.get("yourVariable");
        }
    })