Introduction

EJS stands for Embedded JavaScript. It is a simple templating language that lets you generate HTML markup with plain JavaScript.

Basic Syntax

Script Tags

  • <% %> - Executes JavaScript code (no output)
  • <%= %> - Outputs HTML (adds to result)

Variable Output

Output a variable’s value:

<h1><%= title %></h1>

Loop Example

Iterate through an array and create list items:

<h1><%= title %></h1>
<ul>
<% for(var i=0; i<supplies.length; i++) {%>
    <li><%= link_to(supplies[i], 'supplies/'+supplies[i]) %></li>
<% } %>
</ul>

Include Other Templates

Include a partial template:

<% include ../partials/nav.ejs %>

Helper Functions

Creates an anchor (<a>) tag:

<%= link_to(name, url) %>

Example usage in a loop:

<h1><%= title %></h1>
<ul>
<% for(var i=0; i<supplies.length; i++) {%>
    <li><%= link_to(supplies[i], 'supplies/'+supplies[i]) %></li>
<% } %>
</ul>

img_tag

Creates an image tag:

<%= img_tag('images/maid.png') %>

Reference