What is the proper way to check for existence of variable in an EJS template (using ExpressJS)?

前端 未结 13 1933
一向
一向 2020-12-12 16:02

On the EJS github page, there is one and only one simple example: https://github.com/visionmedia/ejs

Example

<% if (user) { %>
    

&

相关标签:
13条回答
  • 2020-12-12 16:36

    I've come across the same issue using node.js with mongoose/express/ejs when making a relation between 2 collections together with mongoose's populate(), in this case admins.user_id existed but was related to an inexistant users._id.
    So, couldn't find why:

    if ( typeof users.user_id.name == 'undefined' ) ...
    

    was failing with "Cannot read property 'name' of null" Then I noticed that I needed to do the checking like this:

    if ( typeof users.user_id == 'undefined' ) ...
    

    I needed to check the "container" of 'name', so it worked!
    After that, this worked the same:

    if ( !users.user_id ) ...  
    

    Hope it helps.

    0 讨论(0)
  • 2020-12-12 16:37

    I have come up with another solution.

    <% if(user){ %>
       <% if(user.name){ %>
         <h1><%= user.name %></h1>
    <%}}%>
    

    I hope this helps.

    0 讨论(0)
  • 2020-12-12 16:38

    To check if user is defined, you need to do that:

    <% if (this.user) { %>
       here, user is defined
    <% } %>
    
    0 讨论(0)
  • 2020-12-12 16:39

    You can use this trick :

    user.name // stops code execution,if user is undefined
    (scope.user||0).name // === undefined
    

    where scope is parent object of user

    0 讨论(0)
  • 2020-12-12 16:41

    The same way you would do it with anything in js, typeof foo == 'undefined', or since "locals" is the name of the object containing them, you can do if (locals.foo). It's just raw js :p

    0 讨论(0)
  • 2020-12-12 16:41

    What I do is just pass a default object I call 'data' = '' and pass it to all my ejs templates. If you need to pass real data to ejs template, add them as property of the 'data' object.

    This way, 'data' object is always defined and you never get undefined error message, even if property of 'data' exist in your ejs template but not in your node express route.

    0 讨论(0)
提交回复
热议问题