Labs ICT
Pro Login

EJS with Express

Setting EJS as the view engine.

Setting Up EJS with Express

Express has built-in support for EJS. You just tell it to use EJS as the view engine and point it to your views folder.


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

app.set("view engine", "ejs");
app.set("views", "./views");

app.get("/", function(req, res) {
  res.render("index", { title: "Home" });
});

app.listen(3000);
    

That's it. Express will look for .ejs files in the views folder and render them automatically.

The res.render Method

res.render() is how you send a rendered template to the browser. Pass the template name and a data object.


app.get("/profile", function(req, res) {
  res.render("profile", {
    username: "bilal",
    joined: "2024-01-15",
    posts: 42
  });
});
    

Express finds views/profile.ejs, renders it with the data, and sends the HTML as the response.

Passing Data to Templates

The data object you pass to res.render() becomes available in the template through the output tags.


<!-- views/user.ejs -->
<div class="profile">
  <h1><%= user.name %></h1>
  <p>Email: <%= user.email %></p>
  <p>Member since: <%= user.since %></p>
</div>
    

Your route handler decides what data to pass. The template just displays it. This separation keeps your code organized.

Using Partials

EJS lets you include other template files with <%- include('header') %>. This is great for headers, footers, and navbars.


<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
</head>
<body>
  <%- include('partials/navbar') %>

  <main>
    <h1><%= title %></h1>
    <p>Page content goes here.</p>
  </main>

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

Partials keep your templates DRY. Write once, include everywhere.

Global Variables and Middleware

You can make data available to every template using app.locals or middleware. This is perfect for site-wide info like the site name or current user.


app.locals.siteName = "My App";
app.locals.year = new Date().getFullYear();

app.use(function(req, res, next) {
  res.locals.currentUser = req.user || null;
  next();
});

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

app.locals and res.locals are automatically available in all templates. No need to pass them manually on every route.

Try it Yourself →