简体   繁体   中英

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM