Programming

EJS 템플릿 (ExpressJS 사용)에서 변수의 존재를 확인하는 적절한 방법은 무엇입니까?

procodes 2020. 8. 14. 21:07
반응형

EJS 템플릿 (ExpressJS 사용)에서 변수의 존재를 확인하는 적절한 방법은 무엇입니까?


EJS github 페이지에는 하나의 간단한 예제가 있습니다 : https://github.com/visionmedia/ejs

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

이것은 user라는 변수의 존재를 확인하는 것으로 보이며 존재하는 경우 몇 가지 작업을 수행하십시오. 응?

내 질문은 왜 사용자 변수가 존재하지 않으면 Node가 ReferenceError를 던질까요? 이것은 위의 예를 쓸모 없게 만듭니다. 변수의 존재를 확인하는 적절한 방법은 무엇입니까? try / catch 메커니즘을 사용하고 ReferenceError를 잡아야합니까?

ReferenceError: user is not defined
    at IncomingMessage.anonymous (eval at <anonymous> (/usr/local/lib/node/.npm/ejs/0.3.1/package/lib/ejs.js:140:12))
    at IncomingMessage.<anonymous> (/usr/local/lib/node/.npm/ejs/0.3.1/package/lib/ejs.js:142:15)
    at Object.render (/usr/local/lib/node/.npm/ejs/0.3.1/package/lib/ejs.js:177:13)
    at ServerResponse.render (/usr/local/lib/node/.npm/express/1.0.7/package/lib/express/view.js:334:22)
    at Object.<anonymous> (/Users/me/Dropbox/Projects/myproject/server.js:188:9)
    at param (/usr/local/lib/node/.npm/connect/0.5.10/package/lib/connect/middleware/router.js:146:21)
    at pass (/usr/local/lib/node/.npm/connect/0.5.10/package/lib/connect/middleware/router.js:162:10)
    at /usr/local/lib/node/.npm/connect/0.5.10/package/lib/connect/middleware/router.js:152:27
    at Object.restrict (/Users/me/Dropbox/Projects/myproject/server.js:94:5)
    at param (/usr/local/lib/node/.npm/connect/0.5.10/package/lib/connect/middleware/router.js:146:21)

나는 단순히 내 서버 코드에 "사용자"지역 변수를 추가함으로써이 오류를 없앨 수 있다는 것을 이해하지만, 여기서 요점은 매일 if / else를 사용하여 런타임에 이러한 변수의 존재를 확인하고 싶다는 것입니다. nullcheck 유형 패턴. 존재하지 않는 변수에 대한 예외는 나에게 우스꽝스러워 보입니다.


js, typeof foo == 'undefined'또는 "locals"가 그것들을 포함하는 객체의 이름이기 때문에 당신은 할 수 있습니다 if (locals.foo). 그것은 원시 js입니다 : p


변수 앞에 locals

예: if(locals.user){}


<% if (locals.user) { %>

 // Your logic goes here 

<% } %>

사용자가 정의되었는지 확인하려면 다음을 수행해야합니다.

<% if (this.user) { %>
   here, user is defined
<% } %>

"obj === void 0"을 확인하는 뷰 도우미를 만들 수 있습니다. 이것은 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;
}

그런 다음보기에서 사용하십시오.

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

mongoose의 populate ()와 함께 2 개의 컬렉션 사이에 관계를 만들 때 mongoose / express / ejs와 함께 node.js를 사용하는 동일한 문제가 발생했습니다.
따라서 이유를 찾을 수 없습니다.

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

"null의 '이름'속성을 읽을 수 없습니다"로 실패했습니다. 그런 다음 다음과 같은 검사를 수행해야한다는 것을 알았습니다.

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

'이름'의 '컨테이너'를 확인해야했기 때문에 효과가있었습니다!
그 후 이것은 동일하게 작동했습니다.

if ( !users.user_id ) ...  

도움이 되었기를 바랍니다.


대답을 위해이 페이지에 왔지만 다음과 같은 더 짧은 인라인 구문을 생각해 냈습니다.

 <h2><%= user.name ? property.escrow.emailAddress : '' %></h2>

당신을 위해 if문 당신은 사용할 필요가 typeof:

<% if (typeof user == 'object' && user) { %>

<% } %>

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.


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:

<table>
    <tr>
        <td> Name:</td>
        <td> <%=survey_result&&survey_result.name%></td>
    </tr>
    <tr>
        <td> Dojo Location:</td>
        <td> <%=survey_result&&survey_result.dojo_loc%></td>
    </tr>
    <tr>
        <td> Favourite Language:</td>
        <td> <%=survey_result&&survey_result.fave_lang%></td>
    </tr>

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

When I tried it with previously suggested ways, just:

<% if (typeof survey_result !== undefined) { %>
... <!-- some js and/or html code here -->
<% } %>

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.

참고URL : https://stackoverflow.com/questions/5372559/what-is-the-proper-way-to-check-for-existence-of-variable-in-an-ejs-template-us

반응형