Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 374
Industrial Avatar asked Dec 18 '11 14:12

Industrial


People also ask

What is Mustache in Nodejs?

Mustache is a logic-less template syntax. It can be used for HTML, config files, source code — anything. It works by expanding tags in a template using values provided in a hash or object. It is often referred to as “logic-less” because there are no if statements, else clauses, or for loops.

What is Mustache JS used for?

Mustache is an open source logic-less template engine developed for languages such as JavaScript, Ruby, Python, PHP, Java and many more. It's a very lightweight, readable syntax with a comprehensive specification. Mustache can be used for HTML, config files, and source code.

How handlebars JS is different from Mustache JS?

js and Mustache are both logicless templating languages that keep the view and the code separated like we all know they should be. Handlebars differs from its predecessor in that, within Block Expressions (similar to sections in Mustache), Helpers allow custom function through explicit user-written code for that block.

What is Mustache programming?

Mustache is a logic-less templating system. It permits you to use pre-written text files with placeholders that will be replaced at run-time with values particular to a given request. For more general information on Mustache, consult the mustache specification.


1 Answers

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... 
});
like image 61
diff_sky Avatar answered Oct 09 '22 09:10

diff_sky