EJS에서 반복문으로 콘텐츠 출력하기

developsy·2022년 7월 10일
0

EJS에서는

<% %>

안에 자바스크립트 코드를 사용할 수 있다.

하나의 값을 불러올 때는 <%= %>를 사용하고, 자바스크립트 구문을 사용할 땐 <% %>를 사용한다. 문법은 나중에 더 알아봐야겠다.

        <% for (const restautrant of restaurants){ %>
        <li class="restaurant-item">
          <article>
            <h2>Restaurant Title</h2>
            <div class="restaurant-meta">
              <p>Mexican</p>
              <p>Address of the restaurant, including city</p>
            </div>
            <p>
              A short description, explaining why this restaurant is awesome!
            </p>
            <div class="restaurant-actions">
              <a href="">View Website</a>
            </div>
          </article>
        </li>
        <% } %>

이런 식으로 EJS에선 HTML 콘텐츠를 반복할 수 있다. 이제 불러온 restaurant에서

[
  {
    "name": "aaaa",
    "address": "bbbb",
    "cuisine": "cccc",
    "website": "https://naver.com",
    "description": "eeee"
  }
]

각 key별로 값에 접근할 수 있다.

이때 render메서드에 삽입하는 객체에도 restaurants 배열을 추가해줘야 한다.

const storedRestaurants = JSON.parse(fileData);
    res.render('restaurants', { numberOfRestaurants: storedRestaurants.length, restaurants: storedRestaurants});

이렇게 되면

배열에 저장된 데이터가 HTML에 출력 된다. 배열에 데이터를 추가하면 반복적으로 추가될 것이다.

  • if문을 사용한다고 하면
    <% if (numberOfRestaurants === 0){ %>
    <p>we have no restaurant yet...</p>
    <% } else {%>
    ...
    <% } %>

이런 식으로 여는 중괄호와 닫는 중괄호를 주의하면서 사용하면 된다.

profile
공부 정리용 블로그

0개의 댓글