Dust your views
In our node js application, we can use variety of templating engines like “jade” , “ejs”, “mustache” etc.
Dust.js is an asynchronous templating engine which can be used both on server side as well as client side and provide easy caching with high performance.
In my previous blog on EJS as a templating engine, i have mentioned how we can use “ejs” to render views in an express application. Similarly, we can use dust for rendering templates as it emphasize on presentation rather than the application and business logic.
To use dust in our application, we need to write this line in our app.js file,
[js]
var app = express();
app.set(‘view engine’, ‘dust’);
[/js]
A sample dust file (demo.dust) will look like:
[js]
<html>
<body>
Hello {name}!!
</body>
</html>
[/js]
Now when we render this file and pass some JSON data along with it:
[js]
res.render(‘demo’, {name: "Sakshi"});
[/js]
The output will be:
Hello Sakshi!!
So here we can see, how the passed JSON data is used in the dust file.
Some of the commonly used operators or tags in dust are:
1. { } is used as a replace operator.
2. {#fruits}{name}{~n}{/fruits} is the syntax to loop through an array named ‘fruits’.
3. {?name}…{:else}…{/name} is used for conditional if else logic implementation.
4. {name|s|h|u} is used to apply various filters. For example “s” is used to disable auto-escaping.
Likewise we have plenty of other tags through which we can use “dust” for templating our views effectively.
Hope this will help 🙂