Skip to content

EJS-Embedded JavaScript templating by ejs.co

December 21, 2022 | 12:00 AM

EJS

ejs

Table of Content

Install

npm install ejs

Use

Pass EJS a template string and some data. BOOM, you’ve got some HTML.

let ejs = require("ejs");
let people = ["geddy", "neil", "alex"];
let html = ejs.render('<%= people.join(", "); %>', { people: people });

Docs

Example

<% if (user) { %>
  <h2><%= user.name %></h2>
<% } %>

Usage

let template = ejs.compile(str, options);
template(data);
// => Rendered HTML string

ejs.render(str, data, options);
// => Rendered HTML string

ejs.renderFile(filename, data, options, function (err, str) {
  // str => Rendered HTML string
});

Options

Tags

Includes

Includes are relative to the template with the include call. (This requires the ‘filename’ option.) For example if you have “./views/users.ejs” and “./views/user/show.ejs” you would use <%- include(‘user/show’); %>.

You’ll likely want to use the raw output tag (<%-) with your include to avoid double-escaping the HTML output.

<ul>
  <% users.forEach(function(user){ %>
    <%- include('user/show', {user: user}); %>
  <% }); %>
</ul>

Layouts

EJS does not specifically support blocks, but layouts can be implemented by including headers and footers, like so:

<%- include('header'); -%>
<h1>
  Title
</h1>
<p>
  My page
</p>
<%- include('footer'); -%>

Exercise 1:

Render a file and pass a value to it

index.ejs

<!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.0" />
    <title>To do list</title>
  </head>
  <body>
    <!-- <%= variable name %> -->
    <h1>Its a <%= kindOfDay %></h1>
  </body>
</html>

app.js

const express = require("express");
const app = express();

const PORT = 3000;

// mmiddleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static("public"));
app.set("view engine", "ejs");

const today = new Date().getDay();
let kindOfDay;
if (today === 6 || today == 0) {
  kindOfDay = "weekend";
} else {
  kindOfDay = "weekday";
}

app.get("/", (req, res) => {
  res.render("index", { kindOfDay });
});

app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});

Exercise 2:

simple code in ejs

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To do list</title>
</head>

<body>
    <% if( kindOfDay=== 'weekend') { %>
        <h1 style="color: purple">Its a <%= kindOfDay %></h1>
    <% } else { %>
        <h1 style="color: red">Its a <%= kindOfDay %></h1>
    <% } %>
</body>

</html>

Exercise 3:

index.ejs

<!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.0" />
    <title>To do list</title>
  </head>

  <body>
    <% if( kindOfDay==='weekend' ) { %>
    <h1 style="color: purple">Its a <%= kindOfDay %></h1>
    <% } else { %>
    <h1 style="color: red">Its a <%= kindOfDay %></h1>
    <% } %>

    <ul>
      <% items.forEach(item=>{ %>
      <li><%= item %></li>
      <!-- <%= item %> HTML escaped -->
      <% }) %>
    </ul>

    <form action="/" method="post">
      <input type="text" name="newItem" />
      <button type="submit" name="button">Add</button>
    </form>
  </body>
</html>

app.js

const express = require("express");
const app = express();

const PORT = 3000;

// mmiddleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static("public"));
app.set("view engine", "ejs");

const items = ["Buy food", "Cook food", "Eat food"];

const today = new Date().getDay();
let kindOfDay;
if (today === 6 || today == 0) {
  kindOfDay = "weekend";
} else {
  kindOfDay = "weekday";
}

app
  .route("/")
  .get((req, res) => {
    res.render("index", { kindOfDay, items });
  })
  .post((req, res) => {
    const { newItem } = req.body;
    items.push(newItem);
    res.redirect("/");
  });

app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});

Exercise 4:

Layout in ejs

header.ejs

<!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.0" />
    <link rel="stylesheet" href="css/styles.css" />
    <title>Tot do list</title>
  </head>

  <body></body>
</html>

Footer.ejs

</body>
<footer>
    &#169; Copyright 2023 Codethatdev
</footer>
</html>

index.ejs

<%- include('header'); -%>
<div class="box" id="heading">
  <h1>Its a <%= kindOfDay %></h1>
</div>

<div class="box">
  <% items.forEach(item=>{ %>
  <div class="item">
    <input type="checkbox" />
    <p><%= item %></p>
  </div>
  <% }) %>

  <form class="item" action="/" method="post">
    <input
      type="text"
      name="newItem"
      placeholder="Add new item"
      autocomplete="off"
    />
    <button type="submit" name="button">+</button>
  </form>
</div>

<%- include('footer'); -%>