Reputation: 1042
I have a simple Handlebars template at email-template.hbs
that I'd like to precompile and load into my app.js
file without reading from the filesystem and compiling it every time app.js
is run.
Right now, I have something that looks like this:
var handlebars = require('handlebars');
var fs = require('fs');
var source = fs.readFileSync('./email-template.hbs', 'utf-8');
var template = handlebars.compile(source);
I'd rather have something like this:
var handlebars = require('handlebars');
var template = require('email-template');
Where email-template.js
is the precompiled email-template.hbs
template.
Upvotes: 7
Views: 6105
Reputation: 256
I'm new to Node and Handlebars, and had the same question.
The trick is to precompile your template using the -c
flag (which precompiles to Node's CommonJS module format, and gives it the path to the handlebars runtime module it needs).
Given you've already followed the directions for setting up precompilation (npm install handlebars -g
), then for your example of generating email-template.js
from ./email-template.hbs
, try running this on the command line:
handlebars ./email-template.hbs -f ./email-template.js -c handlebars/runtime
...which should produce an email-template.js
with
var Handlebars = require("handlebars/runtime"); var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
at the top. Then you can use it in your app.js
like so:
var Handlebars = require('handlebars/runtime');
var hbtemplate = require('./email-template.js');
// You don't even seem to need the "var hbtemplate =" above,
// as precompiling puts your template into the Handlebars object.
var template = Handlebars.templates['email-template'];
// ...then you can use template(data) to generate the HTML string
Upvotes: 24
Reputation: 17168
Just make yourself a helper function:
// requireHbs.js
var handlebars = require('handlebars');
var fs = require('fs');
var memoize = require('lodash.memoize');
module.exports = memoize(function requireHbs(templateName){
var filename = './' + templateName + '.hbs';
var source = fs.readFileSync(filename, 'utf-8');
return handlebars.compile(source);
});
Then use it like this:
// app.js
var requireHbs = require('./requireHbs');
var template = requireHbs('email-template');
Upvotes: -1