본문 바로가기

NodeJS/pug

pug json파일 읽어서 pug로 던지고 뿌리기

node.js에서 express로 간편하게 잡고, view파일은 pug로 사용중인데 DB사용까진 안해도 될거 같아서 json으로 작성한뒤 pug index파일로 뿌리려고 하는데~ 엄청나게 안되다가 해결했습니다. 눈물날거 같군...

 

js/example.json

[
  {
    "thumbnailImg" :"/img/thumbnailImg01.jpg",
    "cardText" : "카드 텍스트 1",
    "cardTextNum" : "A-1",
    "textMuted" : "2020-11-09"
  },
  {
    "thumbnailImg" :"/img/thumbnailImg02.jpg",
    "cardText" : "카드 텍스트 2",
    "cardTextNum" : "A-2",
    "textMuted" : "2020-11-10"
  }
]

routes/inde.js

router.get('/', function(req, res, next) {
  fs.readFile('./public/js/example.json', (err, data) => {
    if(err) throw err;
    const results = JSON.parse(data.toString());
    res.render('index', { title:"WEB Designer", results });
  });
});

view/index.pug

each item in results
  div(class="col-md-3")
    div(class="card mb-4 shadow-sm")
      svg(class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: Thumbnail")
        title Placeholder
        rect(width="100%" height="100%" fill="#55595c")
        text(x="35%" y="50%" fill="#eceeef" dx="1.5em" dy=".4em") #{item.cardTextNum}
         
      div(class="card-body")
        p(class="card-text") #{item.cardText}
        div(class="d-flex justify-content-between align-items-center")
          div(class="btn-group")
          small(class="text-muted") #{item.textMuted}

forEach로 했는데도 값이 안뽑혀서 아이고 미치겠네~~ 하다가... 결국 pug의 문법을 제대로 알지 못해서 일어났던일....(ㅠㅠ) 포인트는!!!

each item in results

이것, each item in results 이것을 써주는 것입니다.

each 변수이름 in json데이터

 

그리고 json파일에서 뽑아온 변수(?)에 맞게....

저 같은 경우는 #{item.cardTextNum}, #{item.cardText}, #{item.textMuted} 이런 애들이요. pug파일에 보이시죠?

아무튼.. 안될때는 고생하지말고 제발 구글 검색!! 검색부터 먼저 하기~~!!

 

참고 사이트 : 

pugjs.org/language/iteration.html

 

Iteration – Pug

Iteration Pug supports two primary methods of iteration: each and while. each Pug’s first-class iteration syntax makes it easier to iterate over arrays and objects in a template: ul each val in [1, 2, 3, 4, 5] li= val 1 2 3 4 5 You can also get the index

pugjs.org

riptutorial.com/pug/example/29501/each-iteration

 

pug - Each iteration | pug Tutorial

pug documentation: Each iteration

riptutorial.com

 

728x90
300x250