Template Engines in Express.js

📘 Express.js 👁 54 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

A template engine allows you to generate dynamic HTML pages by embedding JavaScript logic into HTML.
Instead of sending static HTML files, you can render pages with data from your server, making your web applications interactive.

Express supports multiple template engines, such as:

  • EJS – Embedded JavaScript templates

  • Pug – Clean, indentation-based syntax

  • Handlebars – Logic-less templates


1. Setting Up a Template Engine

We’ll use EJS as an example.

  1. Install EJS:

npm install ejs
  1. Set EJS as the view engine in app.js:

const express = require('express'); const app = express(); const port = 3000; // Set EJS as template engine app.set('view engine', 'ejs'); // Define a route app.get('/', (req, res) => { res.render('index', { title: 'Home Page', message: 'Welcome to Express.js!' }); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

2. Project Structure

express-app/ │ ├─ views/ │ └─ index.ejs │ └─ app.js

views/index.ejs:

<!DOCTYPE html> <html> <head> <title><%= title %></title> </head> <body> <h1><%= message %></h1> </body> </html>
  • <%= %> – Output the value of a variable.

  • <% %> – Execute JavaScript code without rendering output.


3. Passing Data to Templates

You can pass objects, arrays, and variables to your template:

app.get('/users', (req, res) => { const users = ['Alice', 'Bob', 'Charlie']; res.render('users', { usersList: users }); });

views/users.ejs:

<h1>User List</h1> <ul> <% usersList.forEach(user => { %> <li><%= user %></li> <% }) %> </ul>

4. Using Partials

Partials are reusable pieces of templates, like headers or footers.

views/partials/header.ejs:

<header> <h1>My Website</h1> </header>

views/index.ejs:

<%- include('partials/header') %> <p>Welcome to the homepage!</p>
  • <%- include('file') %> – Includes another template file.


5. Other Popular Template Engines

EngineFeatures
EJSSimple, syntax similar to HTML & JS
PugIndentation-based, clean and concise
HandlebarsLogic-less templates, reusable partials
MustacheMinimalistic and easy to use

6. Key Points

  • Template engines help render dynamic content from the server.

  • Express makes it easy to switch between engines by setting app.set('view engine', 'engineName').

  • Using partials promotes reusable code.

  • Ideal for server-side rendered web applications.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes