Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Using Templating Engines | Serving Static and Dynamic Content
Express.js Essentials for Backend Development

Using Templating Engines

Swipe to show menu

To render dynamic HTML in your Express.js applications, you use a templating engine. Templating engines allow you to embed variables and logic directly into your HTML files, making it easy to create dynamic content that changes depending on data from your server.

Begin by installing a templating engine such as Pug. In your project directory, run:

npm install pug

Next, set up your Express.js app to use Pug as the view engine. This tells Express to use Pug templates for rendering views.

Here is a basic setup:

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

// Set 'views' directory for template files
app.set('views', './views');
// Set Pug as the view engine
app.set('view engine', 'pug');

// Define a route that renders a template with variables
app.get('/', (req, res) => {
  res.render('index', { title: 'Welcome', message: 'Hello, Express with Pug!' });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

You also need a Pug template file. Create a directory called views in your project root, and inside it, add a file named index.pug:

doctype html
html
  head
    title= title
  body
    h1= message
    p This page is rendered using Pug templating engine.

When you visit http://localhost:3000, Express renders the index.pug template, passing it the title and message variables. Pug then generates the final HTML by replacing the variables with their values.

Templating engines work by allowing you to write templates that mix static HTML with placeholders for dynamic data. When a request comes in, Express can call res.render() to process a template file, inject the data you provide, and generate the final HTML response.

You pass data to a template by providing an object as the second argument to res.render(). The keys in this object become variables available inside your template. This approach keeps your application logic separate from your HTML layout, making your code cleaner and easier to maintain.

With templating engines, you can reuse common layouts, include partials, and avoid manual string concatenation. This helps you build complex, data-driven pages efficiently.

question mark

Which of the following best describes the main benefit of using a templating engine like Pug in an Express.js app?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 2

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 5. Chapter 2
some-alt