Skip to content
Advertisement

How can I check if an EJS variable exists?

I used EJS layout in my Node.js application. Currently I faced a problem when data which is required in the EJS file is not available then it simply generate an error. What I want is to add a condition before using the EJS variable in javascript.

Here is my code in which I use EJS variable inside script tag.

JavaScript

here is the code in which I use conditions inside the EJS.

JavaScript

It also shows an error when it do not receive any message variable.

Error which I received is:

JavaScript

Advertisement

Answer

Your if check is incorrect. You can check locals.message or whatever to see if that’s exists, then use it.

For your case it will be:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement