Arthur Zhang
Arthur Zhang

Reputation: 1537

To judge whether a variable in the ejs

Here's my application:

index.js

function index(req, res) {
    res.render('admin/index');
}

module.exports = index;

index.ejs

<%
    if(data) {
%>
        <div class="alert alert-danger" role="alert">login fail</div>
<%
     }
%>

I got an error saying:

data is not defined

I want to check whether the variable exists, and to display the dialog if it does. What should I do?

Upvotes: 2

Views: 2150

Answers (1)

raina77ow
raina77ow

Reputation: 106375

Either rewrite the check as follows:

<% if (typeof data !== 'undefined') { %>

... or check the property on locals (local variables object) instead:

<% if (locals.data) { %>

Explanation: when EJS compiles a template into a function, it does not populate its variables' stack based on the options supplied. Instead, it wraps this function with with statement:

with (locals || {}) {
  (function() {
  // ... here goes the template content
  })();
}

Now, the data object (second parameter of render) is passed into the template function as locals variable, it's against this object all the checks are made. The point is, if accessed somevar is never defined in the local template scope (by var statement), and doesn't exist in locals object either, it'll cause a ReferenceError: somevar is not defined error.

(one can disable with-wrapping, setting _with option of template to false, but by default it's just undefined)

Upvotes: 4

Related Questions