Home / Ejs / EJS Advanced Basics

EJS Advanced Basics

EJS Advanced Basics

Great job learning the fundamentals of EJS! Now that you understand the basic syntax and structure, let's dive deeper into more practical applications and features that will make your templating experience much more powerful.

Working with Arrays and Objects

You already know how to display simple variables. Let's see how to work with more complex data structures:

Arrays

<!-- Display array items -->
<ul>
    <% items.forEach(function(item, index) { %>
        <li><%= index + 1 %>: <%= item.name %></li>
    <% }); %>
</ul>

<!-- Check if array has content -->
<% if (items.length > 0) { %>
    <p>You have <%= items.length %> items</p>
<% } else { %>
    <p>No items found</p>
<% } %>

Objects

<!-- Access object properties -->
<div>
    <h2><%= user.name %></h2>
    <p>Email: <%= user.email %></p>
    <% if (user.profile) { %>
        <p>Occupation: <%= user.profile.occupation %></p>
    <% } %>
</div>

Conditional Logic

EJS makes conditional logic really easy:

<% if (user.isAdmin) { %>
    <button>Edit Profile</button>
<% } else if (user.isPremium) { %>
    <button>Upgrade Account</button>
<% } else { %>
    <button>Create Account</button>
<% } %>

<!-- Multiple conditions -->
<% if (user.age >= 18 && user.hasLicense) { %>
    <p>You can drive!</p>
<% } %>

<!-- Using ternary operator -->
<p>Role: <%= user.role === 'admin' ? 'Administrator' : 'User' %></p>

Looping Through Data

EJS provides several ways to iterate through data:

forEach loops

<ul>
    <% products.forEach(function(product) { %>
        <li><%= product.name %> - $<%= product.price %></li>
    <% }); %>
</ul>

For loop (traditional)

<% for (let i = 0; i < items.length; i++) { %>
    <p>Item <%= i + 1 %>: <%= items[i] %></p>
<% } %>

Template Reuse with Includes

One of EJS's strongest features is the ability to include partial templates:

header.ejs:

<header>
    <h1><%= siteTitle %></h1>
    <nav>
        <a href="/">Home</a>
        <a href="/about">About</a>
    </nav>
</header>

main.ejs:

<% include header %>

<main>
    <h2>Welcome <%= userName %>!</h2>
    <p>This is the main content area.</p>
</main>

EJS with Express.js (Practical Example)

Let's see how this works in a real application:

app.js:

const express = require('express');
const app = express();

app.set('view engine', 'ejs');

// Sample data
const users = [
    { name: "Alice", age: 25, role: "admin" },
    { name: "Bob", age: 30, role: "user" },
    { name: "Charlie", age: 35, role: "moderator" }
];

app.get('/users', (req, res) => {
    res.render('users', { 
        title: "User List",
        users: users,
        currentUser: req.query.user || null
    });
});

app.listen(3000);

views/users.ejs:

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
</head>
<body>
    <h1><%= title %></h1>
    
    <% if (currentUser) { %>
        <p>Showing profile for <%= currentUser %></p>
    <% } %>
    
    <div class="user-list">
        <% users.forEach(function(user) { %>
            <div class="user-card">
                <h3><%= user.name %></h3>
                <p>Age: <%= user.age %></p>
                <p>Status: 
                    <% if (user.role === 'admin') { %>
                        <span class="admin">Administrator</span>
                    <% } else if (user.role === 'moderator') { %>
                        <span class="moderator">Moderator</span>
                    <% } else { %>
                        <span class="regular">Regular User</span>
                    <% } %>
                </p>
            </div>
        <% }); %>
    </div>
</body>
</html>

Error Handling in EJS

Sometimes data might be missing or malformed. Here's how to handle it:

<!-- Safe property access -->
<% if (user && user.profile) { %>
    <p>First name: <%= user.profile.firstName || 'Not provided' %></p>
<% } else { %>
    <p>No profile data available</p>
<% } %>

<!-- Using try/catch in JavaScript blocks -->
<% try { %>
    <p>Total: $<%= calculateTotal(items) %></p>
<% } catch (error) { %>
    <p>Error calculating total: <%= error.message %></p>
<% } %>

Built-in EJS Functions

EJS comes with some useful helper functions:

<!-- Get current date -->
<p>Today is: <%= new Date().toLocaleDateString() %></p>

<!-- Format numbers -->
<p>Price: $<%= price.toFixed(2) %></p>

<!-- String operations -->
<p>User: <%= username.toUpperCase() %></p>

Practical Exercise

Create a simple blog template:

  1. Create an article.ejs file
  2. Include header and footer partials
  3. Display article title, content, author, and date
  4. Add conditional logic for featured articles
  5. Loop through related articles using arrays
  6. Use proper HTML structure with semantic elements

Key Takeaways from This Lesson

  1. Data Handling: EJS excels at displaying complex data structures like arrays of objects
  2. Real-world Logic: You can implement actual business logic directly in templates
  3. Template Reuse: Includes help create consistent, maintainable codebases
  4. Integration Ready: Works seamlessly with Express.js frameworks
  5. Error Resilience: Proper conditionals make your pages more robust

You're now ready to start building real applications using EJS! The next step is to practice with actual projects where you can combine these concepts into meaningful, dynamic web pages.

Keep experimenting and don't hesitate to explore the official EJS documentation for even more advanced features.