How to use express ejs layoutsHi hoping that you are well today, our main focus is on how to use express ejs layouts in building a default nodejs website template.We are going to build a website with three pages with ejs as our default templating languageIn this article here we built a complete MERN stack application with REACT as our default front end libraryBut today we are not going to use any front end library but instead we are going to use a express templating language for the front end that is ejsTemplating engines are used to split elements in web page into multiple components like: footer, header, head, layout etc.So there is no need to rewrite those elements for other pages and that way your application can scale easily.now lets define some of the terms we are going to use in this article.

NodeJS

Is an open source JavaScript runtime environment that allows users to run code on server

Express

Is a nodeJS framework that makes the writing of nodeJS simpler and easier

Ejs

The term EJS stands for Embedded JavaScript templating.EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.

Prerequisites

  • node
  • command line
  • text editor
  • browser

Installing dependencies

In this part we are going to install the dependencies that are going to be used in this projectwe are going to use

  • express
  • ejs
  • express-ejs-layout

Now open the terminal and make a new directory then initialize your project as shown

ian@IanoTech:~/Documents/NODE$ mkdir ejsweb
ian@IanoTech:~/Documents/NODE$ cd ejsweb
ian@IanoTech:~/Documents/NODE/ejsweb$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (ejsweb) 
version: (1.0.0) 
description: 
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /home/ian/Documents/NODE/ejsweb/package.json:

{
  "name": "ejsweb",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes) 
ian@IanoTech:~/Documents/NODE/ejsweb$ 

Now what we’ve done here, we have made a directory named ejsweb then initialized our node project using npm initTo install our dependencies go to the terminal and type the following

npm i express ejs express-ejs-layout

Project set up

In this section we are going to set up our projectwe are going to create some files and directories inside our project folderNow in your project terminal create the following files and directories

ian@IanoTech:~/Documents/NODE/ejsweb$ touch server.js
ian@IanoTech:~/Documents/NODE/ejsweb$ mkdir views
ian@IanoTech:~/Documents/NODE/ejsweb$ mkdir views/layouts
ian@IanoTech:~/Documents/NODE/ejsweb$ touch views/layouts/layout.ejs
ian@IanoTech:~/Documents/NODE/ejsweb$ mkdir views/partials
ian@IanoTech:~/Documents/NODE/ejsweb$ touch views/partials/header.ejs
ian@IanoTech:~/Documents/NODE/ejsweb$ touch views/partials/footer.ejs
ian@IanoTech:~/Documents/NODE/ejsweb$ touch views/index.ejs
ian@IanoTech:~/Documents/NODE/ejsweb$ mkdir views/pages
ian@IanoTech:~/Documents/NODE/ejsweb$ touch views/pages/about.ejs
ian@IanoTech:~/Documents/NODE/ejsweb$ touch views/pages/contact.ejs
ian@IanoTech:~/Documents/NODE/ejsweb$ 

Work well done we have created the necessary files and folders required for this project.

Configuring our server.js file with the dependencies

In the server.js file add the codes below

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

app.set("view engine" , "ejs")
app.set('views', path.join(__dirname, "views"));

app.set("layout", "layouts/layout")
app.use(expressLayouts)

app.get('/' ,(req,res)=>{
    res.render('index')
})






const port =process.env.PORT || 8000;
app.listen(port, ()=> console.log(`app running on ${port}`))

In the codes above i have imported the modules required for the projectCreated our default home page routeOur app is going to run on port 8000after that run the command below in the terminal type node server.jslets set up our layout file

Setting up the layout and header,footer and home page

in the layout.js file add the html structure belowWe are going to use bootstrap in our project so don’t be shocked with the cdn link

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
   
    <title>WEB DESIGN</title>
  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

   
  </head>
  <body>
    <br>
   <br>
    <div class="container">
   

   <%- include('../partials/header.ejs') %>
  <br>
  

  <%- body %>

  <br>
  <br>


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

  <br>
  <br>
</div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

  </body>
</html>

In the file structure above we are going to include the header.js file and footer.js file and then body of the application will come in betweenThe body is the contents in the about,contact or any other page.In our application there will be no need to rewrite our header and footer files since the layout file has got everything covered for usNow let add our html files to the header and the footerheader.ejs

<ul class="nav nav-pills">
  <li role="presentation" class="active"><a href="#">Home</a></li>
  <li role="presentation"><a href="#">About</a></li>
  <li role="presentation"><a href="#">Contact</a></li>
</ul>

footer.ejs

<div class="well">footer class @2022 ALL RIGHTS RESERVED</div>

Then in the index.ejs file which is our main body add the codes below to display

<div class="jumbotron">
  <h2>HELLO, WELCOME TO OUR WEBSITE</h2>
  <p>Happy to have you here</p>
  <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
</div>

Now open the browser on localhost:8000 and see what displays

the actual image display in the browser

we are done with setting the home page which is the index.ejs file, the header and the footernow lets set up the rest of the pages

Pages

in the server.ejs file add the lines belowthese are the respective routes for the about and contact pages


app.get('/about', (req,res)=>{
    res.render('pages/about')

})

app.get('/contact', (req,res)=>{
    res.render('pages/contact')
    
})

Then add the html files below to the about and contact pagesabout

<div class="alert alert-success" role="alert">WELCOME TO THE ABOUT PAGE</div>

Contact

<form>
  <div class="form-row">
    <div class="form-group col-md-6">
      <label for="inputEmail4">Email</label>
      <input type="email" class="form-control" id="inputEmail4" placeholder="Email">
    </div>
    <div class="form-group col-md-6">
      <label for="inputPassword4">Name</label>
      <input type="text" class="form-control" id="text" placeholder="Name">
    </div>
  </div>
  <div class="form-group">
    <label for="inputAddress">Address</label>
    <input type="text" class="form-control" id="inputAddress" placeholder="1234 Main St">
  </div>
  <div class="form-group">
    <label for="inputAddress2">Address 2</label>
    <input type="text" class="form-control" id="inputAddress2" placeholder="Apartment, studio, or floor">
  </div>
  
    
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Then in the header.ejs add the routes to the about and contact anchor tags replace the current header with the following

<ul class="nav nav-pills">
  <li role="presentation" class="active"><a href="/">Home</a></li>
  <li role="presentation"><a href="/about">About</a></li>
  <li role="presentation"><a href="/contact">Contact</a></li>
</ul>

Now break the terminal by pressing ctrl + C then re-run it again using node server.jsrefresh your browser and then try navigating to the respective contact and about page

Job well done we have set up our website template using express ejs layoutsKeep on practicing and add additional pagesThanks for making it up to this point

Posted in
programming

Post a comment

Your email address will not be published.

As the top software development company in Kenya, we can't wait to show you what we can do. Our team of talented designers and developers are passionate about creating beautiful, functional websites that not only look great, but also help your business grow.
0

No products in the cart.

× Get Help?