#5.8 Iteration(반복문)

jini.choi·2022년 7월 11일
0

유튜브 클론코딩

목록 보기
23/27

Iteration(반복문)

https://pugjs.org/language/iteration.html
Pug는 eachwhile을 지원한다.

home template에 videos 보내주기

1. template에는 array인 변수(variable)이 있어야함

videoController.js

export const trending = (req, res) => {
  const videos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; //fakeVideos
  return res.render("home", { pageTitle: "Home", videos });
};

2. each 적고, 보여주고 싶은 variable 이름을 적어줌

home.pug

extends base.pug

block content
    h2 Welcome here you will see the trending videos
    ul
        each video in videos
            li=video
  • 여기서 videos array 안의 각 video element에 대해서, list item을 만들어서 video를 그 안에 넣어주고 있음

  • each video in videosvideo는 다른이름으로 해도됨(loop 상의 현재 값, 즉 video는 array 안의 각 item을 가르킴)

  • each video in videosvideos는 Controller 부분의 videos와 같아야 함

배열이 비어있다면?

  • if문을 사용하여 영상이 없을 시 안내문구를 작성한다.

videoController.js

export const trending = (req, res) => {
  const videos = []; //fakeVideos
  return res.render("home", { pageTitle: "Home", videos });
};

home.pug

extends base.pug

block content
    h2 Welcome here you will see the trending videos
    ul
        each video in videos
            li=video
        else   
            li Sorry nothing found.
  • 즉, pug는 자동적으로 videos 안에 뭐가 있는지 없는지 체크함. 없는지 체크하기 위해선 li Sorry nothing found.를 작성
profile
개발짜🏃‍♀️

0개의 댓글