Express.js hbs module - register partials from .hbs file Express.js hbs module - register partials from .hbs file express express

Express.js hbs module - register partials from .hbs file


For convenience, registerPartials provides a quick way to load all partials from a specific directory:

var hbs = require('hbs');hbs.registerPartials(__dirname + '/views/partials');

Partials that are loaded from a directory are named based on their filename, where spaces and hyphens are replaced with an underscore character:

template.html      -> {{> template}}template 2.html    -> {{> template_2}}login view.hbs     -> {{> login_view}}template-file.html -> {{> template_file}}

Cheers!


This code loads all the partial templates in a directory and makes them available by filename:

var hbs = require('hbs');var fs = require('fs');var partialsDir = __dirname + '/../views/partials';var filenames = fs.readdirSync(partialsDir);filenames.forEach(function (filename) {  var matches = /^([^.]+).hbs$/.exec(filename);  if (!matches) {    return;  }  var name = matches[1];  var template = fs.readFileSync(partialsDir + '/' + filename, 'utf8');  hbs.registerPartial(name, template);});


Looks like creating a variable and pulling in the template code manually works:

var hbs = require('hbs')  , fs = require('fs')  , headerTemplate = fs.readFileSync(__dirname + '/views/_header.hbs', 'utf8');

and later:

hbs.registerPartial('headPartial', headerTemplate);