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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With