EJS Cheatsheet - EJS Template Engine Reference
This reference is for Node and Express developers who render pages serverside with EJS, the template engine you configure in one line and use everywhere. It covers the tag syntax (<% code %>, <%= escaped output %>, <%- raw HTML %>, <%- include %>, comments), how to branch and loop over the locals you pass in, splitting pages into includes, sharing a layout, and calling res.render from Express. Unlike a generic EJS primer, entries are grouped by what each part of the template does, and note when output is escaped vs raw. After reading you should be able to build an Express view, loop over data with <%- for %>, escape user content with <%=, and reuse header/footer via includes.
Basic Syntax 5
<% code %><%= value %><%- value %><%# comment %><%_ code %>Conditionals 3
<% if (condition) { %>...<% } %><% if (condition) { %>...<% } else { %>...<% } %><% if (a) { %>...<% } else if (b) { %>...<% } else { %>...<% } %>Loops 4
<% for (let i = 0; i < items.length; i++) { %>...<% } %><% items.forEach(item => { %>...<% }) %><% for (const item of items) { %>...<% } %><% for (const key in obj) { %>...<% } %>Includes 4
<%- include("header") %><%- include("footer") %><%- include("sidebar", { user }) %><%- include("partials/nav") %>Layout & Inheritance 3
<%- body %><% layout("layout") -%><%- include("header", {title: "Home"}) %>Common Tricks 5
<%= user?.name || "Guest" %><%= JSON.stringify(data) %><%= new Date().toLocaleDateString() %><%= items.join(", ") %><%= Math.round(price * 100) / 100 %>Express Integration 4
app.set("view engine", "ejs")res.render("index", { title: "Home" })app.set("views", "./views")res.render("users/list", { users })Render API & Config 7
ejs.render(str, data)ejs.renderFile("tpl.ejs", data, (err, html) => {})ejs.compile(str, { client: true })ejs.render(str, data, { cache: true })ejs.delimiter = "$"<%= locals.user %>const fn = ejs.compile(str); fn(data)Tips
- <%= %> auto-escapes HTML to prevent XSS; <%- %> outputs raw HTML without escaping.
- include loads synchronously, inserting the included template at the current position.
- EJS supports full JavaScript syntax inside <% %>.
- Layout inheritance needs the express-ejs-layouts middleware, or include header/footer manually.
- Cache templates for performance: app.set('view cache', true).
- Disable cache in dev: app.set('view cache', false) so edits apply immediately.
- Functions from ejs.compile run in the browser, fitting client-side rendering.
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us