Template Engine in Express Js

  • A template engine is a module that allows you to dynamically generate HTML pages by embedding variables and control structures within the HTML markup. Template engines help separate the presentation logic from the application logic, making it easier to manage and render dynamic content. Express.js supports a variety of template engines, and one popular choice is Embedded JavaScript (EJS). Let's explore the concept of template engines in Express.js using EJS as an example.
What is a Template Engine?
  • A template engine is a programming language or library designed to combine templates with a data model to produce documents. In the case of web development, these templates are often HTML files where you can embed dynamic content and logic using placeholders.
Using EJS as a Template Engine in Express.js
  • Step 1: Install EJS


    npm install ejs

  • Step 2: Set EJS as the View Engine in Express.js
    • In your main app file (e.g., `app.js`):


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

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

    • This code tells Express.js to use EJS as the template engine.
    • Step 3: 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 template, `<%= title %>` and `<%= message %>` are placeholders that will be replaced with actual data when the template is rendered.
    • Step 4: Render the EJS Template in Express.js

        // 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: 'Express.js Template Engine',
                message: 'Using EJS as the template engine.'
            });
        });

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

    • In the route handler, `res.render('index', { title, message })` tells Express.js to render the `index.ejs` template, passing an object containing data that will be used in the template.
    • Step 5: 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.
    • Key Concepts in EJS:
    • <%= %> (Escaped Output): This syntax is used to embed the result of evaluating a JavaScript expression into the HTML. It automatically escapes HTML entities to prevent cross-site scripting (XSS) attacks.
    • <%- %> (Raw Output): This syntax is used to embed the result of evaluating a JavaScript expression into the HTML without escaping. Be cautious when using raw output to avoid XSS vulnerabilities.
    • <% %> (Control Flow): This syntax is used for control flow statements in JavaScript, such as loops and conditionals.
    • EJS allows you to seamlessly mix HTML and JavaScript in your templates, making it a powerful tool for creating dynamic web pages in Express.js. Other template engines, such as Pug (formerly Jade), Handlebars, and Mustache, follow similar principles but may have different syntax and features. The choice of a template engine often depends on personal preference and project requirements.

    No comments:

    Post a Comment

    Primitive Types in TypeScript

    In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...