Industrial
Industrial

Reputation: 42798

Using mustache.js along with node.js?

After becoming fond with mustache.js template-style, I would like continue using it in node.js.

I've been able to install it and confirm that it's working, but I just can't get my head around how to use it to template files.

How do I load a template called template.html and apply mustache's magic to it within node.js?

Upvotes: 15

Views: 10453

Answers (2)

Industrial
Industrial

Reputation: 42798

I ended up making a tiny helper function to load a template file as a string;

function loadTemplate(template) {
    return this.fs.readFileSync(app.set('views') + template+ '.html').toString();
}

var html = Mustache.to_html(loadTemplate('myView'), {key: "value", ...});

res.send(html);

Upvotes: 7

diff_sky
diff_sky

Reputation: 561

fs.readFileSync is the synchronous version of fs.readFile, so it will be blocking. Here's a basic example of how you could use fs.readFile with mustache.js which would return the mustache template in the callback.

var object_to_render = {key: "value", ...};

fs.readFile(path_to_mustache_template, function (err, data) {
  if (err) throw err;
  var output = Mustache.render(data.toString(), object_to_render);

  // do something with output... 
});

Upvotes: 21

Related Questions