Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 871
David Findlay Avatar asked Aug 31 '26 01:08

David Findlay


1 Answers

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.

like image 132
David Findlay Avatar answered Sep 02 '26 05:09

David Findlay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!