Embedded JavaScript templates EJS
EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. No religiousness about how to organize things. No reinvention of iteration and control-flow. It's just plain JavaScript.
Installation
npm install ejs
Features
- Fast compilation and rendering
- Simple template tags: <% %>
- Custom delimiters (e.g., use [? ?] instead of <% %>)
- Sub-template includes
- Ships with CLI
- Both server JS and browser support
- Static caching of intermediate JavaScript
- Static caching of templates
- Complies with the Express view system
Simple example:
<html lang="en">
<%- include("./partials/head.ejs") %>
<body>
<%- include("./partials/nav.ejs") %>
<div class="blogs content">
<h2>All Blogs</h2>
<% if (blogs.length > 0) { %>
<% blogs.forEach(blog => { %>
<h3 class="title"><%= blog.title %></h3>
<p class="snippet"><%= blog.snippet %></p>
<% }) %>
<% } else { %>
<p>There are no blogs to display...</p>
<% } %>
</div>
<%- include("./partials/footer.ejs") %>
</body>
</html>
In this example we create three html partials file head.ejs, nav.ejs, footer.ejs. In this partials files is the code that we include on all pages, there is head info, nav links and footer info. We can use <%- %> for importing files.
Blog array are sended in app.js with express render method like :
app.get('/', (req, res) => {
const blogs = [
{title: 'Ttile 1', snippet: 'Text 1'},
{title: 'Ttile 2', snippet: 'Text 12'},
{title: 'Ttile 3', snippet: 'Text 3'},
];
res.render('index', { title: 'Home', blogs });
});
Now we can use this array in index.ejs file. To write js code in file we can use <% %> like in example:
<% if (blogs.length > 0) { %>
<% blogs.forEach(blog => { %>
<h3 class="title"><%= blog.title %></h3>
<p class="snippet"><%= blog.snippet %></p>
<% }) %>
<% } else { %>
<p>There are no blogs to display...</p>
<% } %>
All the Tags we can use:
<%
'Scriptlet' tag, for control-flow, no output
<%_
‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
<%=
Outputs the value into the template (HTML escaped)
<%-
Outputs the unescaped value into the template
<%#
Comment tag, no execution, no output
<%%
Outputs a literal '<%'
%>
Plain ending tag
-%>
Trim-mode ('newline slurp') tag, trims following newline
_%>
‘Whitespace Slurping’ ending tag, removes all whitespace after it