How to use the Pug templating engine in an Express.js application



Image not found!!

Pug (formerly known as Jade) is a popular templating engine for Node.js and Express.js. It allows you to write dynamic HTML templates using a concise and expressive syntax. Here's a step-by-step guide on how to use the Pug templating engine in an Express.js application:

  1. Install Required Packages: Ensure you have Express.js and the Pug templating engine installed. If not, you can install them using npm:

    bash
    npm install express pug
  2. Set Up Your Express App: Create an Express.js application and set up the basic structure. Here's a minimal example:

    javascript
    const express = require('express'); const app = express(); const port = 3000; // Set the view engine to Pug app.set('view engine', 'pug'); // Set the views directory app.set('views', './views'); // Define a route app.get('/', (req, res) => { res.render('index', { title: 'Express with Pug' }); }); // Start the server app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
  3. Create Pug Templates: In the example above, we specified a view engine as 'pug' and set the views directory to './views'. This means that Express will look for Pug templates in the 'views' directory.

    Create a 'views' directory in your project and add a Pug template file, for example, 'index.pug':

    pug
    html head title= title body h1= title p Welcome to #{title}

    This is a basic Pug template that will be rendered when the '/' route is accessed.

  4. Run Your Application: Save your changes and run your Express application:

    bash
    node your-app.js

    Visit http://localhost:3000 in your browser, and you should see the rendered Pug template.

That's it! You've set up an Express.js application using the Pug templating engine. You can now create more complex templates, pass dynamic data to them, and take advantage of Pug's concise syntax for building HTML.