Selected topic

Using Pug

Templating

Prefer practical output? Use related tools below while reading.

What is Pug?

Pug is a high-level, dynamic templating language that allows you to create HTML templates using JavaScript syntax. It's designed to be easy to learn and use, making it a popular choice among web developers.

Why use Pug with Express?

Express.js is a lightweight Node.js framework for building web applications. By combining Pug with Express, you can separate your presentation logic from your application logic, making your code more maintainable and scalable.

Example: Using Pug with Express

Here's an example of using Pug to render a simple HTML template:

Directory structure

markdown
project/
|---- views/
|    |---- index.pug
|---- app.js
|---- package.json

index.pug (template)

pug
html
  head
    title My Page
  body
    h1 Welcome to my page!
    p This is a paragraph of text.

app.js (Express server)

javascript
const express = require('express');
const app = express();

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

app.get('/', (req, res) => {
res.render('index');
});

app.listen(3000, () => {
console.log('Server listening on port 3000');
});


How it works


  1. In the example above, we set express as our templating engine using app.set('view engine', 'pug');.
  2. We create a route for the root URL (/) using app.get('/', (req, res) => { ... });.
  3. Inside the route handler function, we use res.render() to render the index.pug template.
  4. When you navigate to http://localhost:3000, Pug will compile the template and replace placeholders with actual data.

Pug syntax


Here are some basic Pug syntax elements:

  • html: defines an HTML block
  • h1, p: defines a heading or paragraph element, respectively
  • {}: used for string interpolation (e.g., h1= title will render as <h1>title</h1>)
  • =: assigns a value to a variable (e.g., p This is a paragraph of text.)
  • if, for: used for conditional statements and loops, respectively
This example demonstrates the basic usage of Pug with Express. You can explore more advanced features and syntax in the official Pug documentation.