EJS Cheatsheet

Embedded JavaScript templates — tags, partials & helpers

Template
Contents
📝

Basics

<!-- EJS = Embedded JavaScript Templates -->
<!-- File extension: .ejs -->

<!-- Install -->
npm install ejs

<!-- Render from string -->
const ejs = require('ejs');
const html = ejs.render('Hello <%= name %>', { name: 'Alice' });

<!-- Render from file -->
ejs.renderFile('template.ejs', { data }, (err, html) => { });
🏷️

Tags

<!-- Output (escaped) -->
<%= name %>                <!-- HTML-escaped output -->
<%= user.email %>

<!-- Raw output (unescaped) -->
<%- htmlContent %>         <!-- raw HTML -->

<!-- Scriptlet (no output) -->
<% code %>                 <!-- execute JS -->

<!-- Comment -->
<%# This is a comment %>   <!-- not in output -->

<!-- Whitespace control -->
<%_ code _%>               <!-- trim whitespace -->
🔀

Control Flow

<!-- If / Else -->
<% if (user) { %>
  <h1><%= user.name %></h1>
<% } else { %>
  <h1>Guest</h1>
<% } %>

<!-- Loop -->
<ul>
<% items.forEach(function(item) { %>
  <li><%= item.name %> - $<%= item.price %></li>
<% }); %>
</ul>

<!-- For loop -->
<% for (let i = 0; i < 5; i++) { %>
  <p>Item <%= i %></p>
<% } %>

<!-- Ternary -->
<p><%= active ? 'Yes' : 'No' %></p>
🧩

Partials

<!-- Include partial -->
<%- include('header') %>
<%- include('partials/nav') %>

<!-- Include with data -->
<%- include('card', { title: 'Hello', body: 'World' }) %>

<!-- partials/card.ejs -->
<div class="card">
  <h2><%= title %></h2>
  <p><%= body %></p>
</div>
📐

Layout

<!-- views/layout.ejs -->
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body>
  <%- include('partials/header') %>
  <main>
    <%- body %>
  </main>
  <%- include('partials/footer') %>
</body>
</html>

<!-- With express-ejs-layouts: -->
npm install express-ejs-layouts
app.use(require('express-ejs-layouts'));
🚀

With Express

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

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

app.get('/', (req, res) => {
    res.render('index', {
        title: 'Home',
        users: [
            { name: 'Alice' },
            { name: 'Bob' }
        ]
    });
});

// views/index.ejs
<h1><%= title %></h1>
<% users.forEach(u => { %>
  <p><%= u.name %></p>
<% }) %>