Alex Getty
Alex Getty

Reputation: 1727

Rendering templates based on session variable

I am using Meteor, Handlebars, and Backbone to create a multipage application. I have a Router set up using backbone which sets a session variable, currentPage. How can I render a different template depending on the value of currentPage?

I was told that I could create a Template helper function that would do this, but I'm not sure how to approach this.

Upvotes: 2

Views: 634

Answers (3)

Cristian Garcia
Cristian Garcia

Reputation: 9869

The best choice would to use Iron-Router, but it you don't want that here is a nice pattern to change the template:

//HTML
<body>
  {{>mainTemplate}}
</body>

//JS Client Initially
var current = Template.initialTemplate;
var currentDep = new Deps.Dependency;

Template.mainTemplate = function()
{
  currentDep.depend();
  return current;
};

function setTemplate( newTemplate )
{
    current = newTemplate;
    currentDep.changed();
};

//Later
setTemplate( Template.someOtherTemplate );

I don't know how to check for the route but if you can, then you can just use the proposed setTemplate function to change the template conditionally.

Upvotes: 0

TimDog
TimDog

Reputation: 8928

A really simple solution is here: https://gist.github.com/3221138

But I would strongly recommend installing meteor-router. This will require you to first install meteorite.

Also, know that an official routing solution is on the roadmap.

Upvotes: 0

zorlak
zorlak

Reputation: 1404

if currentPage is global and pages are stored as strings, then I would expect this to work:

Handlebars.registerHelper('currentPageIs',function(page){
    return currentPage == page;
});

// and in the html:
{{#if currentPageIs '/posts'}}
    {{> posts}}
{{else}}
    {{> homepage}}
{{/if}}

Upvotes: 1

Related Questions