Views in Express Js

  • In the context of Express.js, "views" refer to the templates or pages that are rendered and sent to the client in response to HTTP requests. Views are a way of dynamically generating HTML or other types of responses based on the application's logic. Templating engines are often used in conjunction with Express.js to facilitate the rendering of dynamic views.
  • Let's go through the steps of setting up views in an Express.js application using a templating engine, such as EJS (Embedded JavaScript).
Step 1: Install Dependencies
  • Install Express and EJS using npm:


    npm install express ejs

Step 2: Project Structure

  • Create a project structure with folders for views and any other necessary modules.


    - my-express-app/
        - views/
            - index.ejs
        - app.js
        - package.json

Step 3: Main App File (app.js)

  • Set up your main app file to use the EJS templating engine and serve views.


    // app.js

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

    // Set the view engine to EJS
    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 Views Example', message: 'Welcome to Express.js!' });
    });

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

Step 4: View File (index.ejs)
  • Create an EJS template file in the "views" folder.

    <!-- 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>


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 view with the message "Welcome to Express.js!"
  • Passing Data to Views: In the example above, data is passed to the view using the `res.render()` method. The data is an object with properties that can be accessed in the view file.
  • Using Layouts: You can use layout templates to structure your views consistently. Libraries like `express-ejs-layouts` can be used for this purpose.

    npm install express-ejs-layouts

  • Then, modify the main app file:

    // app.js

    const express = require('express');
    const expressLayouts = require('express-ejs-layouts');
    const app = express();
    const port = 3000;

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

    // Specify the layout file (default: 'layout')
    app.set('layout', 'layouts/layout');

    app.get('/', (req, res) => {
        res.render('index', { title: 'Express.js Views Example', message: 'Welcome to Express.js!' });
    });

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

  • Create a layout file (`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>

  • Now, your `index.ejs` file can focus on the content without repeating the HTML structure:

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

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


Summary:

  • Views: In the context of Express.js, views are dynamically generated templates or pages sent to the client as responses to HTTP requests.
  • Templating Engine (EJS): Express.js supports various templating engines, such as EJS, which allow you to embed dynamic content in HTML.
  • Rendering Views: Views are rendered using the `res.render()` method in Express.js, and data can be passed to views for dynamic content.
  • Layouts: Layout templates provide a consistent structure for views. Libraries like `express-ejs-layouts` can be used to implement layouts.
  • By incorporating views into your Express.js application, you can create dynamic and interactive web pages that respond to user requests. Templating engines like EJS make it easier to manage and render dynamic content.

No comments:

Post a Comment