Embedded JavaScript EJS Template Engine in Express Js

  • Certainly! Embedded JavaScript (EJS) is a popular template engine for Node.js and Express.js. It allows you to embed JavaScript code directly within HTML markup, making it easy to generate dynamic content. Let's delve into various concepts and examples to understand EJS in detail.
Installation:
  • Before using EJS in your Express.js project, you need to install it:

    npm install ejs


Basic Rendering:

  • Setup EJS in Express:
    • In your main app file (e.g., `app.js`):

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

    // Set EJS as the view engine
    app.set('view engine', 'ejs');

    // Define a route to render the index view
    app.get('/', (req, res) => {
        // Render the 'index' view and pass data to it
        res.render('index', { title: 'EJS Example', message: 'Hello, EJS!' });
    });

    app.listen(port, () => {
        console.log(`Server is running on http://localhost:${port}`);
    });


Create an EJS Template:

  • Create an EJS file (e.g., `views/index.ejs`):

    <!-- views/index.ejs -->

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>
            <%= title %>
        </title>
    </head>

    <body>
        <h1>
            <%= message %>
        </h1>
    </body>

    </html>

  • In this example, `<%= title %>` and `<%= message %>` are EJS tags that will be replaced with actual data when the template is rendered.
Run the Application:
  • Run your application using the command `node app.js` and visit `http://localhost:3000` in your browser. You should see the rendered HTML page with the dynamic content.
EJS Concepts:
  • Escaped Output: Use `<%= %>` for escaped output to prevent HTML entities from being interpreted:

    <!-- views/escapedOutput.ejs -->

    <p>
        Escaped Output: <%= user_input %>
    </p>

  • Raw Output: Use `<%- %>` for raw output if you trust the content (be cautious to avoid XSS vulnerabilities):

    <!-- views/rawOutput.ejs -->

    <p>
        Raw Output: <%- unsafe_html %>
    </p>

  • Control Flow: Use `<% %>` for control flow statements:

    <!-- views/controlFlow.ejs -->

    <% if (condition) { %>
        <p>Condition is true</p>
    <% } else { %>
        <p>Condition is false</p>
    <% } %>
   
    <% for (let i = 0; i < 5; i++) { %>
        <p>Iteration <%= i + 1 %></p>
    <% } %>
 

Layouts and Partials:

  • Layouts: EJS supports layouts for creating consistent structures across views. You can use the `layout` option in Express.js:

    // Set the default layout
    app.set('layout', 'layouts/layout');

    // Use the layout for all views
    app.use(expressLayouts);

  • Create a layout file (e.g., `views/layouts/layout.ejs`):

    <!-- views/layouts/layout.ejs -->

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>
            <%= title %>
        </title>
    </head>

    <body>
        <%- body %>
    </body>

    </html>

  • Partials: You can use partials to reuse components across different views. For example, create a header partial (`views/partials/header.ejs`):

    <!-- views/partials/header.ejs -->

    <header>
        <h1>
            <%= title %>
        </h1>
    </header>

  • Include the partial in a view:

    <!-- views/index.ejs -->

    <%- include('partials/header', { title: 'EJS Example' }) %>

        <body>
            <h1>
                <%= message %>
            </h1>
        </body>

  • Passing Data: Data can be passed from Express.js to EJS templates when rendering views:

    app.get('/dynamic', (req, res) => {
        const data = {
            items: ['Item 1', 'Item 2', 'Item 3'],
            user: { name: 'John', age: 25 },
        };
        res.render('dynamic', data);
    });

  • Use the passed data in the template:

    <!-- views/dynamic.ejs -->

    <ul>
        <% items.forEach(item=> { %>
            <li>
                <%= item %>
            </li>
        <% }) %>
    </ul>

    <p>
        User: <%= user.name %>, Age: <%= user.age %>
    </p>


Summary:

  • Installation: Install EJS using `npm install ejs`.
  • Setup in Express.js: Set EJS as the view engine in Express.js using `app.set('view engine', 'ejs')`.
  • Rendering: Use `res.render()` to render EJS templates and pass data.
  • EJS Concepts: Utilize `<%= %>`, `<%- %>`, and `<% %>` for escaped output, raw output, and control flow.
  • Layouts and Partials: Implement layouts and partials for a consistent structure and reusable components.
  • Data Passing: Pass data from Express.js to EJS templates when rendering views.
Let's explore some more concepts and features in EJS:
  • Custom Functions: You can define custom JavaScript functions and use them in your templates.

    <!-- views/custom_functions.ejs -->

    <% function capitalize(str) { return str.toUpperCase(); } %>

        <p>
            Original: <%= text %>
        </p>
        <p>
            Capitalized: <%= capitalize(text) %>
        </p>

  • Includes and Partials: EJS allows you to include other EJS files in your templates, which is useful for creating modular components.

    <!-- views/main.ejs -->

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>
            <%= title %>
        </title>
    </head>

    <body>

        <%- include('partials/header') %>

            <main>
                <!-- Main content goes here -->
            </main>

        <%- include('partials/footer') %>

    </body>

    </html>

  • Dynamic Partials: You can dynamically choose which partial to include based on conditions or data.

    <!-- views/dynamic_partial.ejs -->

    <%- include(`partials/${templateName}`) %>

  • Client-Side EJS: EJS templates can be used on the client-side as well, allowing for dynamic rendering in the browser.

    <!-- views/client_side_ejs.ejs -->

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>
            <%= title %>
        </title>
    </head>

    <body>

        <script type="text/javascript" src="ejs.min.js"></script>

        <script type="text/javascript">
            var template = "<h1><%= message %></h1>";
            var data = { message: "Hello from EJS on the client side!" };

            var renderedHTML = ejs.render(template, data);
            document.body.innerHTML = renderedHTML;
        </script>

    </body>

    </html>

  • Escaping HTML: By default, EJS escapes HTML content to prevent XSS attacks. However, you can use `<%- %>` for raw HTML output when needed.

    <!-- views/escaping_html.ejs -->

    <p>
        Escaped: <%= user_input %>
    </p>
    <p>
        Raw: <%- unsafe_html %>
    </p>

  • Error Handling: EJS supports error handling within templates using the `<% try { %>` and `<% catch (e) { %>` blocks.

    <!-- views/error_handling.ejs -->

    <% try { %>
        <p>
            This code might throw an error: <%= undefinedVariable %>
        </p>
    <% } catch (e) { %>
        <p>
            Error: <%= e.message %>
        </p>
    <% } %>

  • Custom Delimiters: You can customize the delimiters used by EJS, which is helpful if you need to integrate EJS with other templating engines.

    // In your Express app setup
    app.set('view engine', 'ejs');
    app.set('views', path.join(__dirname, 'views'));
    app.locals.delimiters = '<% %>'; // Set custom delimiters

  • Then, in your EJS templates:

    <!-- views/custom_delimiters.ejs -->

    <% if (condition) { %>
        <p>Custom Delimiters</p>
    <% } %>

  • These are some advanced concepts and features that you can leverage while working with EJS in Express.js. By incorporating these techniques into your templates, you can create more dynamic, modular, and feature-rich views for your web applications.
  • EJS provides a flexible and powerful way to create dynamic HTML content in Express.js applications. By understanding these concepts, you can build expressive and maintainable views for your web applications.

No comments:

Post a Comment