whenever life put's you in a tough situtation, never say why me! but, try me!

Title: Using EJS with Express.js

EJS (Embedded JavaScript) is a simple templating language that lets you generate HTML markup with plain JavaScript. This chapter will guide you through setting up EJS with Express.js, creating dynamic content, managing layouts and partials, and following best practices for building efficient web applications.


A. Introduction to EJS Template Engine

EJS is a popular template engine for Node.js that allows you to embed JavaScript code within your HTML. It's easy to use and integrates well with Express.js, making it a great choice for rendering dynamic web pages.

  • Key Features of EJS:

    • Embed JavaScript directly within your HTML templates.
    • Supports template inheritance and partials for code reuse.
    • Lightweight and fast, with minimal syntax.
  • Example of EJS Syntax:

    <h1><%= title %></h1>
    <p>Welcome to <%= websiteName %>!</p>
    

    Explanation:
    EJS uses <%= %> to output the value of a variable and <% %> to run JavaScript code without outputting it.


B. Setting Up EJS with Express.js

To use EJS in your Express.js project, you'll need to install it and configure Express to use EJS as the view engine.

  • Steps to Set Up EJS:

    1. Install EJS:

      npm install ejs
      
    2. Configure Express.js to Use EJS:

      const express = require("express");
      const path = require("path");
      const app = express();
      
      // Set EJS as the view engine
      app.set("view engine", "ejs");
      
      // Define the directory where the templates are stored
      app.set("views", path.join(__dirname, "views"));
      
      app.get("/", (req, res) => {
        res.render("index", { title: "Home Page", websiteName: "MyWebsite" });
      });
      
      const PORT = 3000;
      app.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
      });
      
    3. Create Your EJS Templates:

      • Create a views directory in your project root.
      • Add a file index.ejs inside the views directory:
        <h1><%= title %></h1>
        <p>Welcome to <%= websiteName %>!</p>
        

    Explanation:
    The res.render() method is used to render the index.ejs template and pass variables to it. EJS then generates the HTML based on the provided data.


C. Creating Dynamic Content with EJS

EJS allows you to create dynamic content by embedding JavaScript logic directly within your templates. You can pass variables, use control flow statements, and loop through data structures.

  • Passing Data to EJS Templates:

    app.get("/about", (req, res) => {
      res.render("about", {
        title: "About Us",
        description: "This is an about page created using EJS.",
      });
    });
    
  • Using Variables and Loops in EJS:

    <h1><%= title %></h1>
    <p><%= description %></p>
    
    <ul>
      <% ['Express', 'EJS', 'Node.js'].forEach(function(item) { %>
        <li><%= item %></li>
      <% }); %>
    </ul>
    

    Explanation:
    In this example, the about.ejs template uses the title and description variables passed from the route handler. It also demonstrates a loop to iterate over an array and render a list of items.


D. Using EJS Layouts and Partials

Layouts and partials in EJS help you organize your code by allowing you to reuse common elements like headers, footers, and navigation menus across multiple pages.

  • Creating a Layout Template:

    <!-- views/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>
      <link rel="stylesheet" href="/styles.css">
    </head>
    <body>
      <header>
        <h1>My Website</h1>
        <nav>
          <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/about">About</a></li>
            <li><a href="/contact">Contact</a></li>
          </ul>
        </nav>
      </header>
    
      <main>
        <%- body %>
      </main>
    
      <footer>
        <p>&copy; 2024 My Website</p>
      </footer>
    </body>
    </html>
    
  • Extending the Layout in Other Templates:

    app.get("/contact", (req, res) => {
      res.render("contact", {
        title: "Contact Us",
        body: `<h2>Contact Us</h2><p>Feel free to reach out to us via email.</p>`,
      });
    });
    

    Using Partials:

    • Partials are small reusable templates that can be included in other templates.
    <!-- views/header.ejs -->
    <header>
      <h1>My Website</h1>
      <nav>
        <ul>
          <li><a href="/">Home</a></li>
          <li><a href="/about">About</a></li>
          <li><a href="/contact">Contact</a></li>
        </ul>
      </nav>
    </header>
    
    • Include a partial in another template:
    <%- include('header') %>
    
    <main>
      <h2>Contact Us</h2>
      <p>Reach out to us via the contact form.</p>
    </main>
    

    Explanation:
    The layout.ejs template acts as a base layout. Other templates like contact.ejs can extend this layout. Partials like header.ejs can be reused across multiple pages by including them.


E. Best Practices with EJS

  • Organize Your Templates:
    Structure your EJS files in a way that is easy to navigate. Use folders for different sections of your site and keep your layouts, partials, and pages organized.

  • Use Layouts and Partials Effectively:
    Make use of layouts and partials to avoid repeating code. This not only reduces redundancy but also makes your codebase easier to maintain.

  • Minimize JavaScript in Templates:
    Keep your business logic separate from your templates. The EJS templates should focus on rendering HTML, while the application logic should reside in your route handlers or controllers.

  • Avoid Inline Styles and Scripts:
    Keep your styles in CSS files and your scripts in JavaScript files. This practice enhances the maintainability of your code and ensures a clean separation of concerns.

  • Handle Errors Gracefully:
    Always include error handling when rendering templates to prevent your application from crashing if something goes wrong.


Conclusion

EJS is a versatile and straightforward template engine that integrates seamlessly with Express.js. By understanding how to set up and use EJS, you can create dynamic, reusable, and maintainable web applications. The use of layouts, partials, and best practices will help you build scalable applications that are easy to maintain and extend.