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

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

    You can create a view helper which checks for "obj === void 0", this one is for express.js:

    res.locals.get = function() {
        var args = Array.prototype.slice.call(arguments, 0);
        var path = args[0].split('.');
        var root = this;
        for (var i = 0; i < path.length; i++) {
            if(root[path[i]] === void 0) {
                return args[1]?args[1]:null;
            } else {
                root = root[path[i]];
            }
        };
        return root;
    }
    

    Then use it in the view like

    <%- get('deep.nested.non.existent.value') %>  //returns: null
    <%- get('deep.nested.non.existent.value', "default value") %> //returns: default value
    

提交回复
热议问题