Master EJS template engine with Node.js and Expressjs

Petros Koulianos
Mar 10, 2020 · 7 min read
Photo by Jon Tyson on Unsplash

1.Introduction

EJS is among the most popular tempate view engines for node.js and expressjs with 4.2k stars at github and over 5.5m downloads per week at npm.

  • <%= Outputs the value into the template (HTML escaped)
  • <%- Outputs the unescaped value into the template
<% if (message) { %>
<h2><%= message.name %></h2>
<% } %>

2. Partials

In this section we’ll learn how to use <%- include(‘’)-%> tag.

startEJS
|--public
|--views
|--pages
|--home.ejs
|--template
|--head.ejs
|--nav.ejs
|--footer.ejs
|--index.js
|--package.json
cd startEJS
npm i express
npm i ejs
const express = require('express')var path = require('path');const app = express();const port = 3000;// view engine setupapp.set('views', path.join(__dirname, 'views'));app.set('view engine', 'ejs');//setup public folderapp.use(express.static('./public'));app.get('/',function (req, res) {res.render('pages/home')});app.listen(port, () => console.log(`MasterEJS app Started on port ${port}!`));
// view engine setupapp.set('views', path.join(__dirname, 'views'));app.set('view engine', 'ejs');
//setup public folderapp.use(express.static('./public'));
app.get('/',function (req, res) {res.render('pages/home')});
<%- include('../template/head')-%><body class="text-center"><div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column"><%- include('../template/nav')-%><main role="main" class="inner cover"><h1 class="cover-heading">MasterEJS</h1><p class="lead">This is a sample app to Master EJS view template engine with Expressjs and Node.js framework</p><p class="lead"><a href="https://medium.com/@pkoulianos/master-ejs-template-engine-with-node-js-and-expressjs" class="btn btn-lg btn-secondary">Read More At Medium</a></p></main><%- include('../template/footer')-%></div></body></html>
node index.js

3. Render Links

In this section, we’ll learn how to render links dynamically.

app.get('/links',function (req, res) {//array with items to sendvar items = [{name:'node.js',url:'https://nodejs.org/en/'},{name:'ejs',url:'https://ejs.co'},{name:'expressjs',url:'https://expressjs.com'},{name:'vuejs',url:'https://vuejs.org'},{name:'nextjs',url:'https://nextjs.org'}];res.render('pages/links',{links:items})});
<%- include('../template/head')-%><body class="text-center"><div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column"><%- include('../template/nav')-%><main role="main" class="inner cover"><h1 class="cover-heading">Example with Links</h1><ul class="list-group"><% links.forEach(function(entry) {%><a href="<%= entry.url%>" class="list-group-item text-dark"><%=entry.name%></a><%});%></ul></main><%- include('../template/footer')-%></div></body><script>//Set active nav linkwindow.onload = function() {document.getElementById('links').classList.add('active');};</script></html>
res.render('pages/links',{links:items});
<% links.forEach(function(entry) {%><a href="<%= entry.url%>" class="list-group-item text-dark"><%=entry.name%></a><%});%>
node index.js
Example with links

3. Render List

In this section, we’ll learn how to render a list dynamically.

app.get('/list',function (req, res) {//array with items to sendvar items = ['node.js','expressjs','ejs','javascript','bootstarp'];res.render('pages/list',{list:items})});
<%- include('../template/head')-%><body class="text-center"><div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column"><%- include('../template/nav')-%><main role="main" class="inner cover"><h1 class="cover-heading">List Example</h1><ul class="list-group"><%list.forEach(function(entry) {%><li class="list-group-item text-dark"><%=entry%></li><%});%></ul></main><%- include('../template/footer')-%></div></body><script>window.onload = function() {document.getElementById('list').classList.add('active');};</script></html>
node index.js
Example with list

4. Render Table

In this section, we’ll learn how to render a table dynamically.

app.get('/table',function (req, res) {//array with items to sendvar items = [{name:'node.js',url:'https://nodejs.org/en/'},{name:'ejs',url:'https://ejs.co'},{name:'expressjs',url:'https://expressjs.com'},{name:'vuejs',url:'https://vuejs.org'},{name:'nextjs',url:'https://nextjs.org'}];res.render('pages/table',{table:items})});
<%- include('../template/head')-%><body class="text-center"><div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column"><%- include('../template/nav')-%><h1 class="cover-heading">Table Example</h1><div class="container bg-light text-dark"><table class="table table-striped"><thead><tr><th>Framework</th><th>URL</th></tr></thead><tbody><%table.forEach(function(entry) {%><tr><td><%=entry.name%></td><td><%=entry.url%></td></tr><%});%></tbody></table></div><%- include('../template/footer')-%></div></body><script>window.onload = function() {document.getElementById('table').classList.add('active');};</script></html>
node index.js
Example with table

4. Render Alert Messages

In this section, we’ll learn how to render a alert messages dynamically.

<%- include('../template/head')-%><body class="text-center"><div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column"><%- include('../template/nav')-%><main role="main" class="inner cover"><%- include('../template/messages')-%><h1 class="cover-heading">Form Example</h1><form method="POST" action="/form"><div class="form-group"><label for="Name">Name</label><input type="text" class="form-control" id="name" name="name" placeholder="Enter Your Name" required></div><div class="form-group"><label for="Surname">Surname</label><input type="text" class="form-control" id="surname" name="surname" placeholder="Enter Surname" required></div><button type="submit" class="btn btn-dark">Submit</button></form></main><%- include('../template/footer')-%></div></body><script>window.onload = function () {document.getElementById('form').classList.add('active');};</script></html>
<!-- Messages Partial Template --><div class="container"><% if(message){ %><div class="alert alert-primary alert-dismissible"><span class="close" onclick="this.parentElement.style.display='none';">&times;</span><strong><%= message.name%> </strong><strong><%= message.surname%></strong></div><% } %></div>
npm i body-parser
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));// parse application/jsonapp.use(bodyParser.json());//our tiny alert message midlewarefunction messages(req,res,next){var message;res.locals.message = message;next();}app.get('/form',messages,function (req, res) {res.render('pages/form');});app.post('/form',function (req, res) {var message=req.body;res.locals.message = message;res.render('pages/form');});
node index.js
Example with form and alert message

5. Conclusion

Get the full sample app from masterEJS.

References

  1. nodejs
  2. ejs
  3. express
  4. getBootstrap

Click here 👇 👇 to sign up and get links behind the medium paywall

Click here to sign up and get all my friend links behind the medium paywall

The Startup

Get smarter at building your thing. Join The Startup’s +724K followers.

Petros Koulianos

Written by

Passionate Developer with main interests: 🔥 JavaScript ⚡ Nodejs 🎽 Running marathons ⛰️ Mountaineering.

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +724K followers.

Petros Koulianos

Written by

Passionate Developer with main interests: 🔥 JavaScript ⚡ Nodejs 🎽 Running marathons ⛰️ Mountaineering.

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +724K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store