express의 template engine 사용하기 (ejs)

스프링에서 많이 사용되는 JSP, Mustache, Thymeleaf와 같은 템플릿 엔진이 express에도 있을 것이라 생각하였다.

그러던 중 강의에서 pug(구 jade)라는 템플릿 엔진을 알게 되었다.

그런데, pug는 마지막 커밋이 꽤나 오래전(약 2년전)이었고 좀 더 많이 사용되는 템플릿 엔진을 찾아보았다.

handlebars나 nunjucks과 같은 템플릿 엔진도 찾을 수 있었지만, 가장 많이 사용되는 ejs를 간단하게 사용해보고 설정과 사용법을 남기도록 하였다.

 

// ./index.js

const express = require("express");
const app = express();

// ejs 설정
app.set("view engine", "ejs"); // ejs를 사용한다.
app.set("views", "./views"); // ejs 파일들이 위치한 폴더를 설정해준다.

일단 ejs를 사용하기 위해서는 express에 설정이 필요하다.

위와 같이 view engine을 ejs로 설정하고, ejs 파일들이 위치하는 폴더를 설정해준다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ejs example</title>
  </head>
  <body>
    <% if (names.length) { %>
      <h1>total: <%= names.length %></h1>
        <ul>
          <% names.forEach(function (name) { %>
            <%# Notice how the single quotation mark is escaped in the output HTML %>
            <li foo='<%= name + "'" %>'><%= name %></li>
          <% }) %>
        </ul>
      <% } %>
  </body>
</html>

그리고 /views/hello.ejs 파일을 위와 같이 작성해준다. (ejs 깃허브의 example 참고)

설정한 위치 내부에 ejs 파일이 위치해야 제대로 동작한다.

 

그리고, 이제 작성한 ejs 파일을 연결해준다.

// ./index.js

// ~ 생략 ~

app.get("/test", (req, res) => {
  res.render("hello.ejs", { names: ["lee", "park", "korea"] });
});

이제 서버를 키고 /test로 접근하면, 작성한 ejs 파일을 확인할 수 있다.

 

res.render를 통해서 ejs 함수를 렌더링할 수 있는데, 첫 번째 인자로 렌더링할 파일의 이름, 두 번째 인자로 함께 제공할 변수를 넣어준다.

넣어준 변수를 바탕으로 ejs 파일의 내부에서 동적으로 html 파일이 만들어질 수 있도록 해준다.

 

 

 

⛈ 참고자료

https://www.npmjs.com/package/ejs

 

ejs

Embedded JavaScript templates. Latest version: 3.1.9, last published: 3 months ago. Start using ejs in your project by running `npm i ejs`. There are 12559 other projects in the npm registry using ejs.

www.npmjs.com

https://github.com/mde/ejs/wiki/Using-EJS-with-Express

 

Using EJS with Express

Embedded JavaScript templates -- http://ejs.co. Contribute to mde/ejs development by creating an account on GitHub.

github.com

 

🌞 ejs의 문법 및 사용법

https://ejs.co/#docs

 

EJS -- Embedded JavaScript templates

Simple syntax JavaScript code in simple, straightforward scriptlet tags. Just write JavaScript that emits the HTML you want, and get the job done!

ejs.co