Skip to content

Instantly share code, notes, and snippets.

@jaksah
Created September 4, 2016 16:31
Show Gist options
  • Save jaksah/70fc400ce70664eaa47fcb47c34b307c to your computer and use it in GitHub Desktop.
Save jaksah/70fc400ce70664eaa47fcb47c34b307c to your computer and use it in GitHub Desktop.
Handlebars - Register all partials in a directory
var fs = require('fs');
var hbs = require('hbs');
// Register Partials
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);
});
@jfoclpf
Copy link

jfoclpf commented Jan 20, 2019

You can also use

const fs = require('fs')
const path = require('path')
const Handlebars = require('handlebars')

const partialsDir = '/path/to/dir'
fs.readdirSync(partialsDir).forEach(filename => {
  if (filename.endsWith('.hbs')) {
    const name = path.parse(filename).name

    Handlebars.registerPartial(
      name,
      fs.readFileSync(path.join(partialsDir, filename), 'utf-8')
    )
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment