[Express] EJS의 조건문과 반복문

Shin Hyun Woo·2022년 12월 5일
0
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>

이 템플릿은 라우터로부터 랜덤한 숫자 Num을 res.render() 메서드의 두번째 인자인 객체의 형태로 전달받고 있다.
그 후 <%= 구문으로 HTML에 출력되고 있다.

EJS if문 조건부 렌더링

근데 만약 이 랜덤한 값이 짝수일 때 h2태그로 짝수인지 홀수인지 출력하려면 어떻게 해야할까?

우선 ejs의 <%=안에는 숫자를 연산도 했었고 지금처럼 변수까지 넣었었다.
그럼 if문을 넣으면 어떨까?
조금 지저분한 코드이긴 하지만 이렇게 넣어보면...

<!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문을 이렇게 사용하는게 맞나..? -->
    <%= if(num % 2 === 0){ %>
    
    <%= } %>
  </body>
</html>

문법 에러가 난다. 즉 if문은 저렇게 사용할 수 없다는 것이다.

그래서 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>That is an even number.</h2>
    <% } else { %>
    <h2>That is an odd number.</h2>
    <% } %>
  </body>
</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문과 동일한 결과를 얻는 삼항 연산자 사용 -->
    <h2>
    <%= num%2 === 0 ? "That is an even number." :"That is an odd number." %>
    </h2>
  </body>
</html>

EJS 반복문

이제 반복문을 알아보자.
우선 /cats 라우터를 생성하고 cats라는 상수에 데이터 베이스에서 가져오는 데이터라고 생각하고 임의의 배열을 할당했다.

app.get("/cats", (req, res) => {
  // 이 임의의 배열은 데이터 베이스에서 가져온다고 가정한다.
  const cats = ["Blue", "Rocket", "Monty", "Stephanie", "Winston"];
  res.render("cats", { cats })
});

그리고 템플릿인 cats.ejs 파일을 생성하고 기본 구조의 HTML을 작성하고 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>
    <!-- 반복문 사용 -->
    <p><%= cats %></p>
  </body>
</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>All Cats</title>
  </head>
  <body>
    <h1>All The Cats</h1>
    <!-- 반복문 사용 -->
    <ul>
    <!-- for...of 문을 사용해서 배열의 요소를 반복시킨다. 이 반복문의 로직은 출력되지 않는다. -->
      <% for (let cat of cats){%>
      <!-- <%= 구문을 사용해서 값이 출력된다. -->
      <li><%= cat %></li>
      <% } %>
    </ul>
  </body>
</html>

반복문을 이용하는데 예시로 든 for...of만 가능한게 아닌 모든 반복문을 위와 같이 사용할 수 있다.

profile
untiring_dev - Notion 페이지는 정리 중!

0개의 댓글