Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load precompiled Handlebars template in Node script?

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.

like image 295
dstaley Avatar asked Aug 31 '15 17:08

dstaley


1 Answers

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
like image 58
Jason A. Avatar answered Oct 13 '22 19:10

Jason A.