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

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

    I had same issue, and luckily, I found that there is also a short-circuit function in JS (I knew there was one in Ruby and some other languages).

    On my server/controller side (this is from Node.js/Express):

    return res.render('result', {survey_result : req.session.survey_result&&req.session.survey_result.survey }); 
    

    See what I did there? The && which follows after a possibly undefined variable (i.e. request.session.survey_result object, which might or might not have form data) is the short-circuit notation in JS. What it does is only evaluate the part that follows the && if the part to the left of the && is NOT undefined. It also does not throw an error when the left part IS undefined. It just ignores it.

    Now, in my template (remember that I passed the object req.session.survey_result_survey object to my view as survey_result ) and then I rendered fields as:

    I used short-circuit there also, just for safe-keeps.

    When I tried it with previously suggested ways, just:

    <% if (typeof survey_result !== undefined) { %>
    ... 
    <% } %>
    

    Sometimes, it would still try to evaluate the properties within the IF statement...Maybe someone can offer an explanation as to why?

    Also, I wanted to correct that undefined needs to be without the single quotes, as I saw done in previous examples. Because the condition will never evaluate to true, as you are comparing a String value 'undefined' with a datatype undefined.

    提交回复
    热议问题
    Name: <%=survey_result&&survey_result.name%>
    Dojo Location: <%=survey_result&&survey_result.dojo_loc%>
    Favourite Language: <%=survey_result&&survey_result.fave_lang%>