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?
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.
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.
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.
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.
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...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With