Juni_Dev_log

[Node.js] ejs include 하는 법 (include 오류) 본문

Debugging (벌레잡기)

[Node.js] ejs include 하는 법 (include 오류)

Juni_K 2021. 1. 30. 16:35

Node.js 를 공부하던 도중

 

ejs include 에서 문제가 발생했다.

 

(before debugging)

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
    <% include ./head.ejs %>
    <body>
        <h2><%=title %></h2>
        
        <% include ./footer.ejs %>
    </body>
</html>
 
 
cs

 

해당 파일을 웹 브라우저 상에 띄우면, 계속 "예상치 못한 '/'문자가 발생했습니다." 라는 오류가 계속해서 나오기 시작했다.

 

이것저것 다 만져보고 수정해봤지만...디버깅이 안되던 도중

 

www.npmjs.com/package/ejs/v/3.1.5

 

ejs

Embedded JavaScript templates

www.npmjs.com

공식 사이트에서 접속해서 확인해보니, ejs 가 버전이 올라가면서 include 하는 방법이 바뀐 것이었다.

 


Includes

Includes either have to be an absolute path, or, if not, are assumed as relative to the template with the include call. For example if you are including ./views/user/show.ejs from ./views/users.ejs you would use <%- include('user/show') %>.

You must specify the filename option for the template with the include call unless you are using renderFile().

You'll likely want to use the raw output tag (<%-) with your include to avoid double-escaping the HTML output.

 

<ul>
<% users.forEach(function(user){ %>
<%- include('user/show', {user: user}) %>  <% }); %>
</ul>

Includes are inserted at runtime, so you can use variables for the path in the include call (for example <%- include(somePath) %>). Variables in your top-level data object are available to all your includes, but local variables need to be passed down.

 

NOTE: Include preprocessor directives (<% include user/show %>) are not supported in v3.0+.

 


2.x 버전에서는 

<% include ./head.ejs %>

 

같은 코드가 작동이 되었지만,

 

 

3.x 버전으로 올라가면서

<%-include('head.ejs') %>

같은 식의 코드로 작성해야 ejs 파일을 참고할 수 있게 되었다.

 

그래서 디버깅 후의 코드는

(After debugging)

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
    <%-include('head.ejs')%>
    <body>
        <h2><%=title %></h2>
        
        <%-include('footer.ejs')%>
    </body>
</html>
cs

 

로 작성해서 돌려보니 정확하게 결과가 나왔다.

'Debugging (벌레잡기)' 카테고리의 다른 글

[Javascript] == 와 === 의 차이  (0) 2021.01.31
Comments