Javascript Templating
Javascript templating is a fast and efficient technique to render client-side view templates with Javascript by using a JSON data source.
Mustache
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.
mustache.js is an implementation of the mustache template system in JavaScript. It is often considered the base for JavaScript templating.
Mustache.render(“Hello, ”, { name: “Sherlynn” });
// returns: Hello, Sherlynn
In the above, we see two braces around . This is Mustache syntax to show that it is a placeholder. When Mustache compiles this, it will look for the ‘name’ property in the object we pass in, and replace with the actual value, e,g, “Sherlynn”.
Mustache is NOT a templating engine. Mustache is a specification for a templating language. In general, we would write templates according to the Mustache specification, and it can then be compiled by a templating engine to be rendered to create an output.
Mustache-Express
Mustache Express lets you use Mustache and Express together easily.
To install:
$ npm install mustache --save
Configure mustache-express in your server.js/app.js/index.js file:
Create a views folder and add some html view templates (e.g. hello.html):
Then in the router configuration, use res.render(TEMPLATE_NAME, JSON_DATA). Example:
res.render('hello', {"name": "Sherlynn"})
Whereby the first parameter ‘hello’ refers to the hello.html file (no need to include the extension (e.g. hello.html) as it has been previously set as html.
The second parameter would be the JSON data itself. We can also pass in a variable representing the data, for example:
var nameObject = {"name": "Sherlynn"}
res.render('hello', nameObject)
Final output: