Search code examples
javascriptnode.jshandlebars.jshandlebarshelper

Is there a way to register a global helper file for Handlebar.js?


I use Handlebar.js to render a template.

function renderTemplate(data, templateName) {
  const html = fs.readFileSync(`${__dirname}/templates/template2.hbs`, 'utf8')

  //register one helper
  hbs.registerHelper("formatName", function () {
    return "This is my jam"
  });

  const template = hbs.compile(html)

  const rendered = template(data)
  return rendered
}

Now as you can see I can register a helper in the function. However, I might write 10-20 helpers. That way this function gets very 'bloated' en unnecessarily large. Is there a way to register a global helper.js file or something a like where I can put all my helpers?


Solution

  • Yes. Handlebars.registerHelper() allows you to pass in an Object and its keys will be registered as helper functions (see the Handlebars docs for more info).

    For example, these two are equivalent:

    Handlebars.registerHelper({
      foo() {},
      bar() {},
    });
    
    Handlebars.registerHelper("foo", function(){});
    Handlebars.registerHelper("bar", function(){});
    

    You could then create a separate JS file that exports this Object. Your renderTemplate file then can import this for use.

    // hbs-helpers.js
    module.exports = {
      foo() {},
      bar() {},
    };
    
    const hbsHelpers = require('./hbs-helpers.js');
    
    function renderTemplate(data, templateName) {
      const html = fs.readFileSync(`${__dirname}/templates/template2.hbs`, 'utf8');
    
      // register ALL helpers
      hbs.registerHelper(hbsHelpers);
    
      const template = hbs.compile(html);
      const rendered = template(data);
    
      return rendered;
    }