Templating Engines with Express.js
Integrate a templating engine (like Pug or EJS) with your Express.js application to dynamically generate HTML content.
Mastering Express.js: Templating Engines
Templating Engines with Express.js
Templating engines allow you to create dynamic HTML content by embedding data into HTML templates. Instead of writing static HTML files, you use placeholders in your templates that are replaced with actual data when the server processes the request. This makes it easier to manage and maintain your web application's presentation layer.
Express.js provides a simple way to integrate with various templating engines like Pug (formerly Jade), EJS, Handlebars, and more. The key is to configure the view engine
and views
directory within your Express application.
Benefits of Using Templating Engines:
- Code Reusability: You can reuse template components across multiple pages.
- Data Separation: Separates data logic from presentation, making code cleaner and easier to maintain.
- Dynamic Content: Easily inject data into HTML based on server-side logic.
- Improved Maintainability: Changes to the layout or structure of your website can be done in the templates, without modifying the server-side code.
Integrating a Templating Engine (EJS) with Express.js
This example demonstrates how to integrate EJS (Embedded JavaScript templates) with an Express.js application. EJS allows you to embed JavaScript directly into your HTML templates.
Step 1: Install EJS
npm install ejs
Step 2: Configure Express.js to use EJS
In your Express application (e.g., app.js
), configure the view engine
to be EJS and specify the directory where your views (templates) are stored.
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
// Set the view engine to EJS
app.set('view engine', 'ejs');
// Set the views directory
app.set('views', path.join(__dirname, 'views'));
app.get('/', (req, res) => {
const data = {
title: 'Welcome to My Express App!',
message: 'This page is rendered using EJS.',
items: ['Item 1', 'Item 2', 'Item 3']
};
res.render('index', data); // Render the 'index.ejs' template with the data
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Step 3: Create an EJS Template (e.g., views/index.ejs
)
Create a file named index.ejs
in a directory named views
. This file will contain your HTML template with embedded JavaScript for dynamic content.
<!DOCTYPE html>
<html>
<head>
<title><%- title %></title>
</head>
<body>
<h1><%- title %></h1>
<p><%- message %></p>
<h2>Items:</h2>
<ul>
<% items.forEach(item => { %>
<li><%- item %></li>
<% }); %>
</ul>
</body>
</html>
Explanation of the EJS Template:
<%- title %>
: This injects the value of thetitle
variable into the HTML. The<%- ... %>
syntax escapes HTML entities. Use<%= ... %>
if you don't want to escape HTML entities.<% items.forEach(item => { %> ... <% }); %>
: This is a JavaScript loop that iterates through theitems
array and generates a list item (<li>
) for each item.
Step 4: Run Your Application
Start your Express.js application. When you navigate to the root route (/
), the server will render the index.ejs
template with the provided data, generating dynamic HTML.
node app.js
Using Pug (formerly Jade)
Pug offers a concise syntax to define HTML structures. Install with npm install pug
and set app.set('view engine', 'pug');
. The views will have a .pug
extension.
Example Pug template (views/index.pug
):
doctype html
html(lang="en")
head
title= title
body
h1= title
p= message
h2 Items:
ul
each item in items
li= item
This Pug template accomplishes the same result as the EJS example. Pug's indented syntax can enhance readability for some developers.