Imagine you have an application computing some values server-side, for example a list of rooms in a chat.
Then you have 2 reasonable solutions :
- send those data as JSON in order for some JavaScript client side to build the list
- generate the list in HTML server side
A templating system is useful for this second solution.
To generate this HTML, instead of having your nodejs program concatenate pieces of HTML, a templating engine is a good solution.
The JS part of the server would generate the data (here using express and fetching the data from a relational database) :
app.get('/rooms', ensureAuthenticated, ensureCompleteProfile, function(req, res){
db.on(req.user.id)
.then(function(uid){
return [
this.listAccessibleRooms(uid),
this.fetchUserPingRooms(uid, 0)
]
}).spread(function(accessibleRooms, pings){
var rooms = {public:[], private:[]};
accessibleRooms.forEach(function(r) {
r.path = roomPath(r);
rooms[r.private?'private':'public'].push(r);
});
res.render('rooms.jade', { rooms:rooms, pings:pings });
}).finally(db.off);
});
and the Jade file would use them :
table.list
each room, i in rooms.public
tr
th: a(href=room.path) #{room.name}
td.rendered #{room.description}
if room.auth
td.role= room.auth
which generates this kind of HTML :
<table class="list">
<tr>
<th><a href="path1">Room 1</a></th>
<td class="rendered">Description of room 1</td>
<td class="role">Admin</td>
</tr>
<tr>
<th><a href="path2">Room 2</a></th>
<td class="rendered">Description of room 2</td>
</tr>
</table>
This separates a little the concerns that are managing the data and displaying them. It also has the advantage of not being too different from HTML which, in my opinion, is good when the goal is to generate HTML.
This example is taken from my open source Miaou chat. The complete Jade file is rooms.jade.