Building Web Applications from Scratch - Part 2: Introduction to Template Engines
Introduction
In the previous part, we introduced web servers with Express and demonstrated how to serve static and dynamic content. However, manually generating HTML using JavaScript strings can quickly become messy and hard to maintain. This is where template engines come in.
A template engine allows you to embed dynamic data inside HTML templates, making it easier to generate web pages dynamically. In this part, we’ll explore how to use a popular template engine called EJS (Embedded JavaScript Templates) with Express.
Why Use a Template Engine?
While you can generate HTML using res.send() in Express, template engines offer several advantages:
- Separation of concerns: Keep HTML separate from business logic.
- Reusable templates: Use layouts and partials to structure your application.
- Improved readability: Avoid messy string concatenation.
Setting Up EJS with Express
Step 1: Install EJS
Run the following command to install EJS:
npm install ejs
Step 2: Configure Express to Use EJS
Modify server.js to set EJS as the view engine:
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
Now, Express will automatically look for EJS templates inside the views folder.
Step 3: Create an EJS Template
Inside a new views directory, create a file called index.ejs with the following content:
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome, <%= name %>!</h1>
<p>This page was generated dynamically using EJS.</p>
</body>
</html>
Step 4: Render the Template from Express
Modify server.js to use this template:
app.get('/', (req, res) => {
res.render('index', { name: 'Guest' });
});
Now, when you visit http://localhost:3000, you will see the HTML rendered with “Welcome, Guest!”
Step 5: Pass Dynamic Data
Modify the route to accept a query parameter:
app.get('/welcome', (req, res) => {
const name = req.query.name || 'Guest';
res.render('index', { name });
});
Now, visiting http://localhost:3000/welcome?name=Paul will display “Welcome, Paul!”
Conclusion
Using a template engine like EJS simplifies HTML generation in web applications. It keeps templates organized, allows for reusability, and improves code maintainability. In the next part, we’ll dive into handling user sessions and authentication. Stay tuned!