David Findlay
David Findlay

Reputation: 1356

Handlebars precompiled to plain HTML

Is there a way to precompile a Handlebars template to plain HTML? Handlebars precompile produces a js file. Can I run that JS on node to produce a HTML file? This is how I'm trying:

// Get a Handlebars instance
var hb = require("handlebars");

// Load a template
import fs = require('fs');
var template:string = fs.readFileSync('templates/template.handlebars','utf8');

// Compile said template
var compiled = hb.precompile(template);

// Write JS file
fs.writeFileSync('compiled/template.js', compiled);

var test = compiled.main();

// Write HTML file
fs.writeFileSync('compiled/template.html', test);

This fails as compiled.main is not a function. There's a main function in there though, which I'm trying to get at.

Upvotes: 5

Views: 4758

Answers (1)

David Findlay
David Findlay

Reputation: 1356

Found the solution. You don't precompile, you just compile and then run the compiled template:

// Get a Handlebars instance
var hb = require("handlebars");

// Load a template
import fs = require('fs');
var template:string = fs.readFileSync('templates/template.handlebars','utf8');

// Compile said template
var compiled = hb.compile(template);
var html = compiled({});

// Write HTML file
fs.writeFileSync('compiled/template.html', html);

Pity it isn't in the docs.

Upvotes: 15

Related Questions