How to use Ejs templates with node js

Embedded JavaScript is abbreviated as EJS. It’s a simple templating language/engine that allows users to produce HTML using only JavaScript. When you need to output HTML with a lot of JavaScript, EJS comes in handy. You’ll learn how to use ejs templates with node js, how to incorporate repeating areas of your site, and how to send data to views in this tutorial.

Prerequisites

  1. A common knowledge of node JS.
  2. A basic knowledge of express JS
  3. Begineer knowledge of HTML

Setting up Project

  • Create an empty directory, name it as u want. I am going to name it as ejs-demo
  • Open it with vs code. You can download vs code from here. https://code.visualstudio.com/
  • Go to terminal by pressing ctrl + shift + ~ and type npm init -y and hit enter. 
  • Go to package.json file and do the following changes. 
  "name": "ejs-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
  • Now go to terminal and type npm i express nodemon cors dotenv ejs and hit enter
  • Create an empty file server.js and put following code inside it.
import express from "express";
import cors from "cors";
import dotenv from "dotenv";

const port = process.env.PORT || 5000;
const app = express();

//setting up template engine
app.set("view engine", "ejs");
//registering middlewares
dotenv.config();
app.use(express.json());
app.use(cors());

//registering routes
// index page
app.get("/", function (req, res) {
  res.render("pages/index");
});

// about page
app.get("/about", function (req, res) {
  res.render("pages/about");
});

//setting up server
app.listen(port, () => {
  console.log(`server is running on port ${port}`);
});

Take note of how the code uses res.render to send a view to the user (). It’s worth noting that res.render() will seek for the view in a views folder. Because the entire URL is views/pages/index, you just need to define pages/index. After that, you’ll use EJS to generate the views.

Now create another directory in the root directory and name it as “views” and then create another directory partials inside views and create the following files inside it.

Head.ejs

<meta charset="UTF-8" />
<title>EJS Tutorial</title>

<!-- Bootstrap CDN -->
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css"
/>

This code contains info for an HTML document’s head. Bootstrap styles are also included. Next, open your code editor and create a new header.ejs file. Add the following lines of code to your project.

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="/">EJS Tutorial</a>
  <ul class="navbar-nav mr-auto">
    <li class="nav-item">
      <a class="nav-link" href="/">Home</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="/about">About</a>
    </li>
  </ul>
</nav>

This code contains a navigation bar. 

Finally, create another file footer.js and put the following content in it

<p class="text-center text-muted">
  © Copyright 2022 Coded With Love❤️ By Anonymous
</p>

You’ve defined three partials. You can now incorporate them in your perspectives. To embed an EJS partial in another file, use <%- include(‘RELATIVE/PATH/TO/FILE’) %>. To tell EJS to render raw HTML, use the hyphen percent instead of just percent. The partial’s path is relative to the currently open file.

Now, create another directory “pages” inside views and add the following files.

Index.ejs

<!DOCTYPE html>
<html lang="en">
  <head>
    <%- include('../partials/head'); %>
  </head>
  <body class="container">
    <header><%- include('../partials/header'); %></header>

    <main>
      <div class="jumbotron">
        <h1>This is Home Page</h1>
        <p>Welcome to Code Techies...</p>
      </div>
    </main>

    <footer><%- include('../partials/footer'); %></footer>
  </body>
</html>

About.ejs

<!DOCTYPE html>
<html lang="en">
  <head>
    <%- include('../partials/head'); %>
  </head>
  <body class="container">
    <header><%- include('../partials/header'); %></header>

    <main>
      <div class="row">
        <div class="col-sm-8">
          <div class="jumbotron">
            <h1>This is about page</h1>
            <p>Welcome to Code techies</p>
          </div>
        </div>

      </div>
    </main>

    <footer><%- include('../partials/footer'); %></footer>
  </body>
</html>

Let’s test

Conclusion

In this tutorial, we saw ejs temples being rendered after going to a specific route. We showed how you can use ejs templates with node js. You are free to browse nodejstutor for more similar tutorials.

Scroll to Top