Lukas
Lukas

Reputation: 10350

Mustache / Handlebars / Hogan templates in separate files in node

I am writing a very simple node app that has a JSON-API, part of that JSON are small bits of HTML. To write templates for the HTML I would live to use a templating engine like Mustache. However, it seems that using Mustache I would have to write my entire templates as strings and pass those on to Mustache. Is it not possible to have a file like myfile.template.js that is an actual Markup / Mustache file that I can import and compile? I would resort to Jade, which still is my fallback, but I feel its syntax and would be less readable than Mustache's, given that my use-case is very small templates.

Upvotes: 0

Views: 223

Answers (1)

Ray Stantz
Ray Stantz

Reputation: 276

I've put my hogan templates in a file, then read them in with fs and called hogan compile at the start of my script. Ends up looking something like:

var doneFile = fs.readFileSync(__dirname + '/templates/html/done.template', 'utf-8');
var doneTemplate = hogan.compile(doneFile);

and then later in this example i call:

res.send(doneTemplate.render({username: req.body.user}));

(the important part being the render call)

Upvotes: 1

Related Questions