Search code examples
javascriptmeteortemplate-enginehandlebars.js

Change / unregister Handlebars helper (Meteor)


Once I register a helper function for Handlebars using Handlebars.registerHelper(), is it possible for me to change and/or remove the helper? Can I just use registerHelper() again to overwrite the current helper, or is there such a thing as Handlebars.unregisterHelper()? Or should I use a different approach if I need a helper to change during an application?

The use case for me is with the Iron Router plugin for Meteor. I am using a layoutTemplate as the general structure of my page. I wanted to use a helper in the layout template right before I yield the main content of the page body (via a <template>, per se) so that each individual template can define its own page title but not have to specify the location in the page every time. For example, my layout template could look like this:

{{pageTitle}}
{{yield}}

And then in the .js file for the rendered template, I would use the following to fill in the {{pageTitle}} placeholder:

Handlebars.registerHelper("pageTitle", function() {
    return "My Page Title";
};

Perhaps there is an alternative way to solve this problem.


Solution

  • What you can do is something like this

    Handlebars.registerHelper("pageTitle", function() {
        return Session.get('pt');
    };
    
    function changePageTitle(str){
        Session.set('pt', str);
    }
    

    Meteor, being reactive, should update the page when a session variable changes. When you switch to another page, simply run changePageTitle.