Home » Node.js

EJS Layouts

EJS Layout: Here, we are going to learn about the EJS Layouts with example.
Submitted by Godwill Tetah, on July 08, 2019

Hi! Welcome. Today, we are going to look at EJS layouts. EJS Layouts make very important use of EJS. Have you ever tried to imagine if social media websites create a new webpage for every user?

Some simply make use of layouts in template engines.

We are going to see an example or possible use of layouts using express and the express-ejs-layouts module.

Take Note! You should have Node.js installed in your before you can start using EJS in this article.

To download Node JS, visit nodejs.org, then install.

* BASIC NODE.JS/EXPRESS KNOWLEDGE REQUIRED

To begin, ensure you have EJS and express installed via npm.

To install EJS, simply open a terminal/command prompt and type the following command:

    npm install ejs
        or
    npm install ejs –save

Equally, install the express-ejs-layouts module using the command npm install express-ejs-layouts.

We will create,

  1. Express server file
  2. Home.ejs file
  3. About.ejs file
  4. Layout.ejs file and all ejs file should be saved in the views folder found in your node.js project directory

Layouts enable us to dynamically fix content or elements to a page in such a way that even if a different page is requested, the content remains but the page is successfully accessed.

Open your text editor and type the following code, save as app.js.

var express = require('express');
var ejs = require('ejs');
var app = express();
var expressLayouts = require('express-ejs-layouts');

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

app.get("/", function(req, res) {
    res.render("home");
});

app.get("/about", function(req, res) {
    res.render("about");
});
app.listen(3000, function() {
    console.log("server is listening!!!");
});

Now, let's create our ejs files:

Open a text editor and type the following code, save as home.ejs

<h4> Home Page</h4>

Open a text editor and type the following code, save as about.ejs

<h5> hi!... I am born again and have been set free!! </h5>

Open a text editor and type the following code, save as layout.ejs

<html>

<head>
    <title> EJS</title>
</head>

<body>
    <div style="background-color:yellow; padding:50;">
        <h2> <center> EJS IS COOL!!</h2>
    </div>
    <%- body %>
</body>

</html>

Finally, initiate the app.js file with node app.js in a terminal and view the port in a browser.

    localhost:3000 and localhost:3000/about

Output:

EJS Layouts 1

EJS Layouts 2

Thanks for coding with me! Feel free to drop a comment or question.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.