Last updated: Apr 5, 2024
Reading time·5 min
if
statement in an EJS templateTo be able to use EJS if-else conditional statements in a Node.js & Express
application, first make sure you have ejs
and
express installed.
# Initialize package.json file npm init -y # Install ejs and express using NPM npm install ejs express # Or using YARN yarn add ejs express
The folder structure for the example is the following.
my-project/ └── index.js └── views/ └── home.ejs
Here is the code for the index.js
file.
// Using ES6 modules import/export syntax import express from 'express'; import path from 'path'; import {fileURLToPath} from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const app = express(); app.use( '/static', express.static(path.join(__dirname, 'public')), ); app.set('view engine', 'ejs'); app.get('/', (req, res) => { res.render('home', { title: 'bobbyhadz.com', message: 'Example message: bobbyhadz.com', salary: 500, }); }); const port = 5000; app.listen(port, () => { console.log(`Example app listening on port ${port}`); });
Make sure to set the type
property to module
in your package.json
file if
you want to use the
ES6 modules import/export syntax.
{ "type": "module", "scripts": {}, "dependencies": {}, // ... }
If you want to use the CommonJS require()
syntax, use the following code
sample instead.
// 👇️ Using CommonJS require() syntax const express = require('express'); const path = require('path'); const app = express(); app.use( '/static', express.static(path.join(__dirname, 'public')), ); app.set('view engine', 'ejs'); app.get('/', (req, res) => { res.render('home', { title: 'bobbyhadz.com', message: 'Example message: bobbyhadz.com', salary: 500, }); }); const port = 5000; app.listen(port, () => { console.log(`Example app listening on port ${port}`); });
Make sure the type
attribute is not set to module
in your package.json
file if you want to use the CommonJS require()
syntax.
And here is the if/else
statement in the home.ejs
file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <h2>bobbyhadz.com</h2> <h2><%= message %></h2> <% if(salary > 0){ %> <h1>Your salary is <%= salary %></h1> <% } else{ %> <h1>Invalid salary supplied. Must be greater than 0.</h1> <% } %> </body> </html>
I can start a development server with npx nodemon index.js
to view the output
at http://localhost:5000.
npx nodemon index.js
Let's go over the if/else
statement.
<% if(salary > 0){ %> <h1>Your salary is <%= salary %></h1> <% } else{ %> <h1>Invalid salary supplied. Must be greater than 0.</h1> <% } %>
The first line checks if the salary
variable is greater than 0
.
We passed the salary
variable to the home.ejs
view in the route handler and
set it to 500
.
app.get('/', (req, res) => { res.render('home', { title: 'bobbyhadz.com', message: 'Example message: bobbyhadz.com', salary: 500, }); });
The next line is the output that is shown if the if
condition is met.
<% if(salary > 0){ %> <h1>Your salary is <%= salary %></h1> <% } else{ %> <h1>Invalid salary supplied. Must be greater than 0.</h1> <% } %>
Then we have an else
statement.
The else
block runs if the if
condition isn't met, in which case the second
h1
element is shown.
In order to test this, I'll set the salary
variable to -100
.
app.get('/', (req, res) => { res.render('home', { title: 'bobbyhadz.com', message: 'Example message: bobbyhadz.com', salary: -100, }); });
If I refresh the page, I can see that the else
block in the EJS template is
run.
You can also use other logic and expressions in your conditional EJS statements.
<% if(new Date().getFullYear() > 2020){ %> <h1>The year is greater than 2020</h1> <% } else{ %> <h1>The year is NOT greater than 2020</h1> <% } %>
We used the Date.getFullYear method to get the current year and compared it to the year 2020.
If I load the code in my browser, I can see that the if
block runs.
if
statement in an EJS templateIf you only want to use an if
statement in your EJS template, use the
following syntax.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <h2>bobbyhadz.com</h2> <h2><%= message %></h2> <% if(salary > 0){ %> <h1>Your salary is <%= salary %></h1> <% } %> </body> </html>
The if
statement checks if the salary
variable is greater than 0
and
prints a message if the condition is met.
You can also use the
ternary operator to
simulate an if/else
statement in an EJS template.
The ternary operator in the example:
salary
variable is greater than 0
.<h2><%- salary > 0 ? 'GT 0' : 'LT or Equal to 0' %></h2>
Here is a nested ternary that is a bit more complex.
<h2> <%- salary > 0 ? 'GT 0' : salary < 0 ? 'LT 0' : salary %> </h2>
The ternary operator:
salary
variable is greater than 0
.GT 0
is returned.salary
variable is less than 0
.LT 0
is returned.salary
variable is returned.switch
statement in an EJS templateYou can also use a switch
statement in your EJS templates.
<% switch (title) { case 'bobbyhadz.com' : %> Site is bobbyhadz.com <% break; case 'example.com' : %> Site is example.com <% break; case 'google.com' : %> Site is google.com <% break; } %>
We passed the value of the title
variable to the switch()
statement.
app.get('/', (req, res) => { res.render('home', { title: 'bobbyhadz.com', message: 'Example message: bobbyhadz.com', salary: 500, }); });
The first case
clause checks if the value of the title
variable is equal to
bobbyhadz.com
and is matched, so the corresponding string is returned and
rendered.
You can also use if/else if/else
conditional statements in your EJS templates.
<% if (salary > 0) { %> <h2>The salary variable is greater than 0</h2> <% } else if (salary < 0) { %> <h2>The salary variable is less than 0</h2> <% } else { %> <h2>The salary variable is equal to 0</h2> <% } %>
The if
statement checks if the salary
variable is greater than 0
.
If the condition is met, the corresponding h2
tag is returned.
The else if
statement checks if the salary
variable is less than 0
.
If neither condition is met, the else
block runs which means that the salary
variable is equal to 0
.
You can learn more about the related topics by checking out the following tutorials: