Reputation: 11095
Suppose I have a template called Navbar
that is included in both Main
and About
pages. In the Navbar
template, I have a search bar component that I want to show only on the Main
template. I define a helper function like below:
Template.Navbar.helpers({
'isMain': function() {
return location.pathname == '/';
}
})
And in the navbar.html,
{{#if isMain}}
<div class="search">search</div>
{{/if}}
This works great as long as you refresh the page. It's because on the main page, Navbar
template is already rendered and when you go to the About
page, it doesn't get re-rendered. As a workaround, I am thinking of enclosing the helper function inside a Template.autorun
.
Q: What exactly is happening here and what's the conventional way of dealing with this kind of problem? I am thinking of doing Session.set("isMain", true)
everytime I go to mainpage.
Upvotes: 3
Views: 52
Reputation: 11095
As @saimeunt suggested, I used Iron Router to fix the issue.
Template.Nav.helpers({
'isMainPage': function(e, template) {
return (Router.current().location.get().path == '/');
}
})
The syntax was a little different but this works because Router
works as a reactive source but location.pathname
does not make the isMainPage
helper reactive.
It is also possible to set Session.set('isMain', true/false)
every time you go navigate to/from the main page and the helper returns Session.get('isMain')
Upvotes: 0
Reputation: 22696
Your isMain
template helper is not reactive, because it's not depending on any reactive data source (querying the location object, which is unreactive).
If you're using iron:router
you could do something like :
Template.Navbar.helpers({
'isMain': function() {
return Router.current().route.getName() == 'main';
}
});
Given that you've declared a main route as follow :
Router.route("/", {
name: "main",
[...]
});
If you're not using iron:router
, you'd have to rely on something else, like a Session
variable to track page change and set its value accordingly.
Upvotes: 3