Using Pug Templates With Express

In my first post about express, I showed you a simple hello world example. All the app did was show the text "Wazzup?"

If we want to make web applications, we need to generate some HTML, and if we want to be able to programmatically customize that HTML while it's still on the server we need a templating language like Pug.

Pug used to be called Jade. In fact, there doesn't seem to be a documentation site with the new name yet. Looks like jade-lang.com is still the spot to go for docs.

Whatever its name is, pug or jade, its a simple templating language you can use to generate HTML. If you'd like to follow along with this example I'm about to throw down, just create a new Node project and install express and pug.

Next, let's create a super-simple template:

html  
  head
    title= title
  body
    h1= message

Create a views directory and save the above file as views/index.pug.

Now let's make our index.js file:

var express = require('express')  
var app = express()  
app.set('view engine', 'pug')

app.get('/', function (req, res) {  
    res.render(
        'index',
        { title: 'Hey Hey Hey!', message: 'Yo Yo'})
})

app.listen(3000, function () {  
    console.log('Example app listening on port 3000!')
})

The HTML that gets rendered to http://localhost:3000/ should look like this:

<html>  
    <head>
        <title>Hey Hey Hey!</title>
    </head>
    <body>
        <h1>Yo Yo</h1>
    </body>
</html>  

Pretty slick right? Instead of having to write brackets as well as opening and closing tags, you can just write the tag name, and that's it! Any dynamic parts you need can just be handed to the rendering engine as an object.

Pug is a language all it's own. There's lots to take advantage of here. I'll go into the details in a later post, maybe a few posts. :)

Looking for a software developer?