Open In App

How to check for undefined property in EJS for Node.js ?

Last Updated : 01 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Handling undefined attributes is essential when working with EJS templates in a NodeJS application to guarantee a seamless and error-free user experience.

In this post, we’ll examine one of the most basic methods for determining whether a variable is defined or not, which involves utilizing a simple if statement.

Approach to check for undefined property in EJS for NodeJS:

Using <% if (variable) { %> Syntax:

The <% if (variable) { %> syntax is a classic way to check for the existence of a variable in an EJS template. This approach is suitable for scenarios where you want to perform a specific action only if the variable is defined.

Steps to Create Node App & Install Required Modules:

Step 1: Firstly, we will make the folder named root by using the below command in the VScode Terminal. After creation use the cd command to navigate to the newly created folder.

mkdir root
cd root

Step 2: Once the folder is been created, we will initialize NPM using the below command, this will give us the package.json file.

npm init -y

Step 3: Once the project is been initialized, we need to install Express and EJS dependencies in our project by using the below installation command of NPM.

npm i express ejs

Project Structure:

PS

The updated depedencies in package.json file will look like:

"dependencies": {
"express": "^4.17.1",
"ejs": "^3.1.6"
}

Example: Let’s create a simple NodeJS application with a route rendering an EJS template that utilizes the if statement to check for undefined properties.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EJS If Statement Example</title>
</head>
 
<body>
    <h1>EJS If Statement Example</h1>
 
    <% if (user && user.username) { %>
        <h2>Hello, <%= user.username %>!</h2>
        <% } else { %>
            <p>Welcome, guest!</p>
            <% } %>
 
</body>
 
</html>


Javascript




const express = require('express');
const app = express();
const port = 4000;
 
// Set EJS as the view engine
app.set('view engine', 'ejs');
 
// Define a route
app.get('/', (req, res) => {
    // Simulate a user object with username
    const user = { username: 'GeeksforGeeks' };
    res.render('index', { user });
});
 
// Start the server
app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});


Start your server using the following command.

node app.js

Output:Visit http://localhost:3000 in your browser to see the example in action.

gfg66

Output

Conclusion:

Using a simple if statement in EJS templates provides a clear and concise way to check for undefined properties. This approach is effective for straightforward scenarios where you want to conditionally render content based on the existence of a variable. In the next parts of this series, we’ll explore additional approaches to handling undefined properties in more complex situations. Remember, choosing the right approach depends on the specific requirements of your application. Stay tuned for more insights into handling undefined properties in EJS for Node.js.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads