In frontend development or Node.js server-side rendering, templating engines are powerful tools for dynamic HTML generation.
Among them, EJS (Embedded JavaScript Templates) stands out. Letβs explore its features, core syntax, and practical use cases!
π₯ Key Features of EJS
- β HTML-like Syntax: Embeds JavaScript directly into HTMLβeasy to learn!
- β Flexibility: Supports conditionals, loops, and partial templates.
- β Dual Compatibility: Works in browsers and Node.js environments.
- β Lightweight: Blazing-fast performance with minimal setup.
π Basic Syntax Crash Course
1οΈβ£ Output Escaped Variables
<h1><%= title %></h1>
<%= %> escapes HTML to prevent XSS attacks.
2οΈβ£ Execute JavaScript Logic
<% if (user) { %>
<p>Welcome, <%= user.name %>! π</p>
<% } %>
<% %> runs JS code without outputting content.
3οΈβ£ Unescaped Output (Caution! β οΈ)
<%- include('header') %>
<%- %> renders raw HTMLβideal for partials but risky with user input.
βοΈ Installation
npm install ejs
π Basic Usage (Node.js + Express)
1οΈβ£ Template File (views/index.ejs)
<!DOCTYPE html>
<html>
<head>
<title><%= pageTitle %></title>
</head>
<body>
<%- include('partials/navbar') %>
<h1>Welcome to <%= siteName %>! π</h1>
</body>
</html>
2οΈβ£ Express Configuration
const express = require('express');
const app = express();
// Set EJS as the template engine
app.set('view engine', 'ejs');
app.set('views', './views');
// Render the template with data
app.get('/', (req, res) => {
res.render('index', {
pageTitle: 'Home',
siteName: 'My Awesome Site π'
});
});
π» Practical Example: Blog Post Listing
π― Implementation Flow
- Prepare Data: Create an array of blog posts in Node.js.
- Pass Data: Use
res.render()to send data to the template. - Render Dynamically: Loop through posts with
forEachin EJS.
π₯οΈ Template (views/articles.ejs)
<% articles.forEach(article => { %>
<div class="article">
<h2><%= article.title %></h2>
<p><%- article.content.substring(0, 100) %>... π</p>
<small>π
Posted: <%= article.date.toLocaleDateString() %></small>
</div>
<% }) %>
π§ Server-Side Code (Express)
app.get('/articles', (req, res) => {
const articles = [
{
title: 'Getting Started with EJS',
content: '<p>EJS simplifies HTML templating! π</p>',
date: new Date('2024-03-01')
},
{
title: 'Node.js Fundamentals',
content: '<ul><li>Event Loop</li><li>Async Patterns</li></ul>',
date: new Date('2024-03-05')
}
];
res.render('articles', { articles });
});
π¨ Generated HTML Preview
<div class="article">
<h2>Getting Started with EJS</h2>
<p><p>EJS simplifies HTML templating! π</p>... π</p>
<small>π
Posted: 3/1/2024</small>
</div>
β Top EJS Features Youβll Love
Partials Reuse:
<%- include('components/footer') %>Custom Delimiters:
ejs.delimiter = '#'; // Change <% to #%Caching for Production:
app.set('view cache', true); // Turbocharge your app! β‘
β οΈ Critical Best Practices
- XSS Protection: Never use
<%- %>with untrusted user input. - Logic Separation: Keep complex calculations in controllers, not templates.
- Performance: Implement pagination for large datasets (>100 items).
π EJS vs. Other Engines
| Feature | EJS | Pug | Handlebars |
|---|---|---|---|
| Syntax | HTML-style | Indentation | Mustache |
| Learning Curve | Low π | Moderate π | Moderate π |
| Partials | β | β | β |
| Async Support | β | β | β |
π Conclusion
EJS shines with its HTML-first approach and minimal learning curve! π―
- Perfect for small to medium projects π οΈ
- Reuse existing HTML/CSS assets β»οΈ
- JavaScript logic feels natural π§
Stay tuned for our advanced guide on layouts, custom helpers, and EJS optimizations! π₯