EJS
Resources:
EJS stands for Embedded JavaScript is a Templating Language. It is a simple templating language that lets us 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.
EJS Features:
- Very Simple Syntax
- Use Plain JavaScript
- Very Fast Compilation and Execution
- Compiles with Express View system
- Caching for template and intermediate JavaScript
- Includes feature available
- Easy Debugging
Getting statrted
npm install -S ejs
const express=require("express");
const path=require("path");
const ejs=require("ejs");
const app=express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
- Create a new folder views, inside folder create a file
index.ejs
//creating route for the root directory
app.get('/', function(req, res){
res.resnder('index');
})
app.listen(3000, function(){
console.log('Now listening on localhost 3000')
})
Injecting values into the views
app.get('/', function(req, res){
res.resnder('index', {
key: 'world';
});
})
<!-- index.ejs file -->
<h1>Hello <%= key%></h1>
<!-- output => 'Hello world' -->
For Loops and Arrays
app.get('/', function(req, res){
res.resnder('index', {
people: [
{name: 'john'},
{name: 'bobby'}
]
});
})
<!-- index.ejs file -->
<ul>
<% for(let person of people) { %>
<li><%= person.name %></li>
<% } %>
</ul>
<!-- output => 'john' 'bobby'-->
If/Else Statement
app.get('/', function(req, res){
res.resnder('index', {
people: [
{name: 'john'},
{name: 'bobby'}
]
});
})
<!-- index.ejs file -->
<ul>
<% for(let person of people) { %>
<% if(person.name === 'john' { %>
<li>This is definitely <%= person.name %>!!!</li>
<% } else { %>
<li>This is definitely not John!!! This is <%= person.name%></li>
<% } %>
<% } %>
</ul>
<!-- output => 'This is definetly john!!!', 'This is definetly not John!!! This is bobby'-->
Syntax EJS
Tags :
<%- ‘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
'<%'
- Outputs a literal
%>- Plain ending tag
-%>- Trim-mode (‘newline slurp’) tag, trims following newline
_%>- ‘Whitespace Slurping’ ending tag, removes all whitespace after it