Overview
Pug or PugJS is a template engine for NodeJS, which allows for server-side rendering of HTML. Unlike standard HTML markup, PugJS allows HTML to be generated dynamically through data sent from the server to the view.
This tutorial uses the example server IP 192.0.2.123.
Prerequisites
Before starting, it is recommended that you:
Set up a non-root user with
sudo
privileges. See our sudo user best practices guide.Have some knowledge with routing in ExpressJS
Verify your server is up to date. Follow our Ubuntu server update best practices.
Make sure build-essential is installed. If not, install it using:
$ sudo apt-get install build-essential
Installation
NodeJS and NPM
Install curl
to be able to install NodeJS from the NodeSource repository:
$ sudo apt-get install curl
Add the latest Active LTS NodeJS repository:
$ curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
And finally, install NodeJS:
$ sudo apt-get install nodejs
Check if everything was installed properly:
$ node -v && npm -v
v12.x.x
6.x.x
Setup
Initialize Development Environment
First, create the project root directory:
$ cd ~
$ mkdir pugjs
$ cd pugjs
Initialize a NodeJS development environment to automatically generate a package.json:
npm init
Answer the short questions to fit your project. For example, if you press return at each question to accept the defaults, the npm init process responds:
About to write to ~/pugjs/package.json:
{
"name": "pugjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)
Install the required packages using npm
in the project root directory:
$ npm install --save express pug
Creating an ExpressJS Web Server
Create an index.js in the root directory of the project:
$ nano index.js
Create a simple ExpressJS web server with the following route in index.js:
const express = require("express");
const port = process.env.PORT || 8080;
const app = express();
app.get('/', (req, res) => {
res.send("It is working!")
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
Running the index.js file with node it should look like this:
$ node index.js
Server started on port 8080
To make sure the routes are working, navigate to the following URL in any browser:
http://192.0.2.123:8080/
You should see 'It is working!' as a response.
Integrating PugJS views with ExpressJS Web Server Routes
Modify the index.js file to accept the pug templating engine and to render a view on a route endpoint:
const express = require("express");
const path = require("path");
const port = process.env.PORT || 8080;
const app = express();
app.set('view engine', 'pug') // sets the view engine
app.set('views', path.join(__dirname, 'views')) // sets the view directory
app.get('/', (req, res) => {
res.render("home") // render view file on this endpoint
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
Now create a directory called views inside the project root directory and cd
into it:
$ mkdir views && cd views
Inside the views folder create a file called home.pug. This file is going to be rendered by the ExpressJS server.
$ touch home.pug
The file structure of the project should look like the following (excluding node_modules and package.json):
~/pugjs/
├── index.js
└── views/
└── home.pug
Edit the home.pug file and add this basic markup inside:
html
head
title Homepage
body
h1 Welcome to the Homepage!
Now, cd
back to the root directory and run the index.js file with node. It should return the same output as before:
$ cd ~/pugjs
$ node index.js
Server started on port 8080
Now navigate to the following URL again in any browser:
http://192.0.2.123:8080/
This time you should see the message 'Welcome to the Homepage!' surrounded with h1 tags.
Sending Data from the Server to the View
To send data to the pug view file, modify the index.js file to send an object to the model:
const express = require("express");
const path = require("path");
const port = process.env.PORT || 8080;
const app = express();
app.set('view engine', 'pug') // sets the view engine
app.set('views', path.join(__dirname, 'views')) // sets the view directory
app.get('/', (req, res) => {
// add a second argument to the render method to send object data to the view
res.render("home", {message: "THIS IS SENT FROM THE SERVER!"}) // render view file on this endpoint
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
Now edit the home.pug file located in the views directory:
html
head
title Homepage
body
h1 Welcome to the Homepage!
p=message
Run index.js with node.
$ cd ~/pugjs
$ node index.js
Server started on port 8080
Navigate to the web server URL. This time you should see 'Welcome to the Homepage!' surrounded with h1 tags and 'THIS IS SENT FROM THE SERVER!' as a paragraph.
Conclusion
You have set up a basic Pug template engine. For more information, please see the Pug API documentation.