Automatic re-rendering: confusion over reactivity

Suppose I have a named template Navbar

that is included in both pages Main

and About

. In the template Navbar

, I have a search bar component that I only want to show on the template Main

. I am defining a helper function as shown below:

Template.Navbar.helpers({
  'isMain': function() {
     return location.pathname == '/';
  }
})

      

And in navbar.html,

{{#if isMain}}
  <div class="search">search</div>
{{/if}}

      

This works great as long as you refresh the page. This is because the template was already rendered on the master page Navbar

, and when you navigate to the page About

, it doesn't get re-rendered. As a workaround, I'm going to include a helper function internally Template.autorun

.

Q: What exactly is going on here and what is the usual way of solving this problem? I think to do it Session.set("isMain", true)

every time I go to the home page.

+3


source to share


2 answers


Your template helper isMain

is unresponsive because it does not depend on any reactive data source (requesting a location object that is inactive).

If you are using iron:router

, you can do something like:

Template.Navbar.helpers({
  'isMain': function() {
     return Router.current().route.getName() == 'main';
  }
});

      



Given that you specified the main route like this:

Router.route("/", {
  name: "main",
  [...]
});

      

If you don't iron:router

, you will have to rely on something else, like a variable Session

, to track the page change and set its value accordingly.

+3


source


As @saimeunt suggested, I used Iron Router to fix the problem.

  Template.Nav.helpers({
    'isMainPage': function(e, template) {
      return (Router.current().location.get().path == '/');
    }
  })

      



The syntax was slightly different, but it works because it Router

works like a reactive source, but location.pathname

doesn't make the header isMainPage

reactive.

Also can be set Session.set('isMain', true/false)

every time you go to / from the homepage and the helper returnsSession.get('isMain')

0


source







All Articles