[Node.js] Express - EJS의 조건문과 반복문

Zero·2023년 3월 13일

Node

목록 보기
8/11
post-thumbnail

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>Random</title>
  </head>
  <body>
    <h1>Your random number is <%= num %></h1>
  </body>
</html>

해당 템플릿은 라우터로부터 랜덤한 숫자 numres.render() 메서드의 두번째 인자인 객체의 형태로 전달받고 있다.

만약 랜덤값을 짝수와 홀수에 따라 html 단에 표시해주고 싶을 때 어떻게 해야할까?

<!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>Random</title>
  </head>
  <body>
    <h1>Your random number is <%= num %></h1>
    <% if(num % 2 === 0){ %>
    <h2>even number.</h2>
    <% } else { %>
    <h2>odd number.</h2>
    <% } %>
  </body>
</html>

다음과 같이 기존 <%= %>에서 <% %> 구문을 통해 출력이 아닌 로직만 처리하는 방식으로 구현할 수 있다.



EJS 반복문

app.get("/cats", (req, res) => {
  // 이 임의의 배열은 데이터 베이스에서 가져온다고 가정한다.
  const cats = ["Blue", "Rocket", "Monty", "Stephanie", "Winston"];
  res.render("cats", { cats })
});
<!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>All Cats</title>
  </head>
  <body>
    <h1>All The Cats</h1>
    <!-- 반복문 사용 -->
    <ul>
    <!-- for...of 문을 사용해서 배열의 요소를 반복시킨다. 이 반복문의 로직은 출력되지 않는다. -->
      <% for (let cat of cats){%>
      <!-- <%= 구문을 사용해서 값이 출력된다. -->
      <li><%= cat %></li>
      <% } %>
    </ul>
  </body>
</html>

--> 다음 결과는


  • /cats 라우터를 생성하고 cats 변수에 배열을 할당해줌
  • 템플릿 cats.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>All Cats</title>
  </head>
  <body>
    <h1>All The Cats</h1>
    <ul>
      <% for (let cat of cats){%>
      <li><%= cat %></li>
      <% } %>
    </ul>
  </body>
</html>

0개의 댓글