Get Started

Including Files

<%- include('partials/navbar.ejs') %>

Include a template with data:

<% include('header', { title: 'My Page' }) %>

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

To include a template, needs a file name option, paths are relative

Method

let ejs = require('ejs');
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
});

Comments

<%# This line will denote a comment %>

<%# This is a multi-line EJS comment.
    It can span multiple lines,
    but will not be displayed 
    in the final HTML output. 
%>

CLI

Render and specify an output file.

$ ejs hello.ejs -o hello.html

Feed it a template file and a data file

$ ejs hello.ejs -f data.json -o hello.html

Variables

<%= var %> Prints the value of the variable
<%- var %> Prints without HTML escaping

Browser Support

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

Use ejs in a script tag.

Render with Data

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

Pass EJS a template string and some data.

Hello world

#install

npm install ejs

#hello.ejs

<% if (user.email) { %>
  <h1><%= user.email %></h1>
<% } %>

#CLI

$ ejs hello.ejs -o hello.html
Comments