This post is part of a Node.js series and is a continuation of my last post, Serving Static Content with Node.js and Express.

In the previous post we served up some static content. Now let’s start making things a little more interesting by serving up some dynamic content. Dynamic content is content that is generated at the time you request the page. So, rather than serving a “hard-coded” html page, we are going to inject dynamic information into the page when it is served.

To do this, we need to use a templating engine to render our dynamic data to the page. There are lots of different templating engines that work with JavaScript including Mustache, Handlebars, EJS, and Pug to name just a few. Each has its own strengths, syntax, logic, and methods of handling data injection.

Templating with Pug

In this tutorial we will be working with a templating engine named Pug, which changed its name from Jade recently after it was learned that Jade was already a registered trademark. Pug has some great features including a clean shorthand for writing HTML markup, templating logic, and the ability to write inline JavaScript.

Installing Pug

We are going to install Pug in the same way the we installed Express earlier in this series, with NPM, so that it saves a reference to the dependency in our package.json file. To do that, run the following in your command line tool:

npm install pug --save

Next, we need to tell Express where to look for our template files, and what templating engine we are using. We are going to do this by setting two Express Application Settings, 'views' and 'view engine' by using the app.set method. This method expects two arguments. The first argument is the name of the property we want to update and the second argument is the value.

First we will update the ‘views’ property and set its value to the path to our views directory. Next we will update the ‘view engine’ property of our and set its value to the name of the templating engine we wish to use, in this case ‘pug’. The code to achieve both of these is below:

app.set('views', 'views');
app.set('view engine', 'pug');

Screen-Shot-2017-11-27-at-13.14.01

This code should come after all dependencies and constants have been defined and before the first app.use line in your index.js file.

A little about Pug syntax

Pug uses its own special markup syntax. Rather that writing standard HTML <opening> and </closing> tags, all we need to write to represnet an HTML element is the tag name. To nest elements, just create a new line and indent the new tagname.

There are two ways to interpolate dynamic data within our template. Assuming that text is a variable that represents some text, we can interpolate its value and render it in our template like so:

p= text

or like this:

p #{text}

The first example is preferred if the variable is the only content in a given element. The second example is preferred if you wish to show a dynamic value within a string of text. Here is another example:

p Here is my #{text}!!!

In this last example, we aren't using = after the tagname because we are displaying some plain text. In the middle of the plain text we are interpolating the variable text, so we are using the #{text} syntax.

Creating your First Pug file

Now, we are going to use Pug to write a basic HTML page in which we can display some dynamic information. Create a file in your views directory and call it hello.pug. Then, add the following code to the file you just created.

html
    head
        title= title
    body
        h1= message

Dont forget, in Pug files, whitespace is important!

The code above will render an html file with a dynamic title and an H1 tag with dynamic text. The last thing we need to do is create a route to serve this template and assign values to title and message.

Rendering Dynamic Data

Now, jump back into your index.js file and let's add a route for ‘/hello’. Let's make this easy by copy/pasting the code that handles our ‘/’ route and making some adjustments. We will need to change ‘/’ to ‘hello’ and instead of using res.sendfile, we are going to use res.render to render our Pug template. res.render expects two arguments. The first is the name of the template file (as a string with no file extension), and the second is an object that contains the data we want to include in the template. Here is the code to do this:

app.get('/hello', function (req, res) {
  res.render('hello', { title: 'Hello', message: 'Hello there!' })
});

In the res.render method, the object we pass in has a title key and a message key that match the variables in our hello.pug file.

That is all we need to render our dynamic data. When you are finished your index.js file should look like this:

var express = require('express');
var app = express();

// view engine setup
app.set('views', 'views');
app.set('view engine', 'pug');

app.use(express.static('public'));

app.get('/', function (req, res) {
  // res.send('Hello World');
  res.sendfile('index.html');
});

app.get('/hello', function (req, res) {
  res.render('hello', { title: 'Hello', message: 'Hello there!' })
});

app.listen(3000, function(){
  console.log("Listening on port 3000!")
});

Now, restart your server and go to http://localhost:3000/hello to see your dynamic content rendered. You've just learned the basics of templating with Pug in an Express application! Way to go! In the next post we'll do some refactoring to move some of the code from our index.js file into separate route and controller files. Coming soon!