Pug.js is a template engine for Node.js and browsers to render dynamic reusable content. At compile time, the template engine compiles our Pug template code to HTML. We can use variables in pug just like in JavaScript. At runtime, the template engine injects or replaces variables in a template file with actual values, and transforms the template into an HTML file which is then rendered on client side.
Pug has many powerful features like conditions, loops, includes, mixins using which we can render HTML code based on user input or reference data. Pug also support JavaScript natively, hence using JavaScript expressions, we can format HTML code. This approach allows us to reuse static web pages having dynamic data.
Pug was formerly called Jade until it’s version 2.0 was released in 2015.
Let’s make a basic pug template using express.js:
Prerequisite: Basic working knowledge of express is required.
Step 1: Make an empty project folder. In command prompt / terminal, run npm init to initialize package.json file:
npm init -y
-y flag is for default settings in package.json.
Step 2: Install express and pug. We will directly install ‘express’ package rather than generating our express app with ‘express-generator’ for simplicity reasons. You can optionally install nodemon for hot reloading.
npm install express pug
Step 3: Make an empty index.js file. Make a views folder and an empty index.pug file inside it. Optionally, you can also make a public folder for static assets like media files and client side javascript.
Our final directory structure will look like this:
Step 4: Setting up a basic express app. In Index.js:
Javascript
// Importing node modules const express = require( "express" ); const pug = require( "pug" ); const path = require( "path" ); // Initializing express app const app = express(); // Setting our view engine to pug app.set( "view engine" , "pug" ); // Setting our default views app.set( "views" , __dirname + "/views" ); // Serving public assets app.use(express.static( path.join(__dirname + "/public" ))); // Home page will render "index.pug" // file. ".pug" extension is not // required. Express takes care of // it behind the scenes app.get( "/" , (req, res) => { res.render( "index" ); }); // Listening our app on port 3000 app.listen(3000); |
Step 5: In index.pug file:
Javascript
doctype html html head title GeeksForGeeks body h1 Welcome to GeeksForGeeks p We successfully made a Sample Pug Template! |
You can read basics of pug syntax here.
Step 6: In terminal start the application. Run nodemon command if we have installed it previously, or just simply use node.
node index.js or nodemon index.js
In browser on localhost 3000 port, we get the below rendered template: