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

前端 未结 13 1980
一向
一向 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:24

    if you plan to use the same object often, you could use a function like this:

    <% function userObj(obj){
        //replace user with what you name your object
        if(typeof user === 'object'){
            let result = user;
            if(obj){
                obj = obj.split('.');
                for(let i = 0; i < obj.length; i++){
                    if(obj[i] && obj[i].trim() !== '' && result[obj[i]]){
                        result = result[obj[i]];
                    }else{
                        result = false;
                        break;
                    }
                }
            }
            return result;
        }
        return false;
    } %>
    

    usage:

    <% if(userObj('name')){
        

    <%= userObj('name') %>

    } %>

提交回复
热议问题