In web development, displaying data from the server on web pages is crucial for creating interactive and dynamic user experiences. This is where Template Engine in Express.js come to the rescue. A Template Engine is a tool that allows you to create dynamic HTML templates by injecting data from the server into HTML code.
Why Use Template Engine?
Template Engine help separate HTML markup from data coming from the server. This allows you to manage HTML code more easily without having to embed data into each line of code. Instead, you'll create "placeholders" or "tags" within the HTML code, which the Template Engine will later fill with server-side data.
Using Template Engine in Express.js
Express.js supports various template engine, such as Pug (formerly known as Jade) and EJS (Embedded JavaScript). Below are examples of using Pug and EJS in Express.js:
Using Pug Template Engine
Install Pug: You need to install the pug
package via npm.
npm install pug --save
Configure Template Engine: In your application's configuration file (e.g., app.js
), define Pug as the template engine.
app.set('view engine', 'pug');
Create a Pug Template: Create Pug files in the views
directory. For example, create an index.pug
file:
doctype html
html
head
title My Express App
body
h1 Welcome to My Express App
p #{message}
Route Handling and Data Rendering: In route handling, you can pass data to the template engine using res.render()
.
app.get('/', (req, res) => {
const message = 'Hello from Express!';
res.render('index', { message });
});
Using EJS Template Engine
Install EJS: Install the ejs
package via npm.
npm install ejs --save
Configure Template Engine: Define EJS as the template engine in your application's configuration.
app.set('view engine', 'ejs');
Create an EJS Template: Create EJS files in the views
directory. For example, create an index.ejs
file:
<!DOCTYPE html>
<html>
<head>
<title>My Express App</title>
</head>
<body>
<h1>Welcome to My Express App</h1>
<p><%= message %></p>
</body>
</html>
Route Handling and Data Rendering: In route handling, pass data to the template engine using res.render()
.
app.get('/', (req, res) => {
const message = 'Hello from Express!';
res.render('index', { message });
});
Conclusion
Using Template Engine in Express.js allows you to create dynamic web pages and display information from the server on the user's browser. By utilizing Pug, EJS, or other template engine, you can build interactive and flexible web pages that provide a better user experience and optimize the management of HTML code and data.