Express Templates

As we have experienced, generating HTML within a node.js/Express server can be painful. Fortunately, there is a solution called templates which allow you to create your HTML as a separate file and have the Express template system bind data to your variables.

There are a plethora templating systems, many of which are cross-platform (moustache) and/or inspired by other platforms (jade/pug). These unfortunately are either complex to setup or require that you learn another language for authoring HTML. Fortunately, there is one system, ejs (embedded JavasScript) which allows regular HTML authoring with the ability to insert simple JavaScript statements which get run on the server side.

The first step to using ejs with Express is to install the module:

npm install ejs

To use ejs in our express app, we set the "view engine" to be "ejs" and then create a template to use

app.set('view engine', 'ejs');
Here is a basic template:
<!DOCTYPE html>
<html lang="en">
<body>
        <h1>My Cool Page</h1>
        <% if (person) {  %>
                <h2><%= person.name %><h2>
                <h3><%= person.other %></h3>
        <% } %>
</body>
</html>
save it as "template.ejs" inside a folder called "views" which is the default.

Then to use a template as the response to a request we do the following:

app.get('/templatetest', function(req, res) {
	var data = {person: {name: "Shawn", other: "blah"}};
    res.render('template.ejs', data);
});
The "render" function takes in the template file and binds the "data" to it. Of course, the "data" can be any data.

To render an array of data:

var data = {people: [{name: "Shawn", other: "blah"}, {name: "Joe", other: "No"}]};
you can use a "forEach" in the template:
<% people.forEach(function(person) {  %>
		<h2><%= person.name %><h2>
		<h3><%= person.other %></h3>
<% }); %>

More Information: Templating with EJS