Home » Node.js

EJS If Else Statement (EJS Conditions)

EJS Conditional statements: In this tutorial, we are going to learn about the conditional statements in EJS (if else statements in EJS) with examples.
Submitted by Godwill Tetah, on July 12, 2019

Hi! Welcome to NODE AND EJS TEMPLATE ENGINE SERIES. Today, we will talk about EJS conditions, that is the if/else statement.

EJS gives us the flexibility to fill it's template depending on a particular condition.

FOR EXAMPLE - Let's assume you have a template for a social media of 12+ (age) users only.

You can control the number of people signing up by placing a condition as seen below,

Take Note! You should have Node.js installed in your before you can start using EJS in this article.

To download Node JS, visit nodejs.org, then install.

* BASIC NODE.JS/EXPRESS KNOWLEDGE REQUIRED

To begin, ensure you have EJS and express installed via npm.

To install EJS, simply open a terminal/command prompt and type the following command:

    npm install ejs
        or
    npm install ejs –save

You can use either command prompt or PowerShell as terminal.

We will create 2 files as usual, one for our express server file and the second our ejs file.

EJS helps us embed JavaScript code, if statements and loops inside html.

Open your text editor and type the following code, save as app.js.

var express = require('express');
var ejs = require('ejs');
var app = express();
app.set('view engine', 'ejs');

app.get("/", function(req, res) { // root route or home route
    res.render("home", {
        age: 16
    });
});
app.listen(3000, function() {
    console.log("server is listening!!!");
});

Unlike any other express app, we used res.render then the ejs file and not res.send.

Also, I didn't require the ejs app. There's no problem!. You can do so if you wish.

Now, let's create our ejs files:

Open a text editor and type the following code, save as home.ejs

<% if (age > 12) { %>
<p> valid!!!</p>
<%} else { %>
<p> Not Allowed </p>
<% } %>

Your ejs file should be saved in the views folder found in your node project directory.

Take Note, the folder name views is not a random word I selected but it's the reserved folder name where express checks for template engine by default.

Finally, initiate the app.js file with node app.js in a terminal and view the port in a browser.
localhost:3000

  • In this example, our condition declares if age variable is greater than 12, let the phrase valid be displayed else, Not allowed phrase will be displayed..
  • Take note of the tags I used in my ejs code.
  • In this case, age is assigned to 12.
  • You can test your own values.

Output

if else in EJS

Thanks for coding with me! Feel free to drop a comment or question.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.