FrontEngineer JungBam

ejs 두번째 변수, js에서 받아서 작업하기 본문

개발일지

ejs 두번째 변수, js에서 받아서 작업하기

정밤톨 2022. 11. 8. 10:52

.render() 두번째 변수로 넘겨준 값을 js파일로 가져오는 작업이 필요했다.

구글링과 유튜브를 아무리 찾아봐도 해당 내용을 찾는 것은 어려웠고 내 방식대로 하나씩 방법을 찾아보기로 했다.

변수를 가져올 수 있는 방법을 하나하나 해보기로..

그러다가 방법을 찾을 수 있었다.

 

서버

router.get('/', async (req, res, next) => {
  try {
    const page = parseInt(req.query.page) || 1;

    const countOfArticles = await db.collection('community').countDocuments();
    const maxIndex = Math.ceil(countOfArticles / 20);

    const query = { deletedAt: null };
    const options = {
      sort: { createdAt: -1 },
      skip: (page - 1) * 20,
      limit: 20,
    };

    const cursor = db.collection('community').find(query, options);
    const articles = await cursor.toArray();

    const board = {
      maxIndex,
      articles,
    };

    res.render('community', board);
  } catch (err) {
    next(err);
  }
});

res.render의 두번째 매개변수로 board를 넘겨주는데 내가 사용하고 싶은 변수는 저 board로 넘어온 딕셔너리 중 maxIndex였다. 저 값을 ejs파일에서 부르는 것은 매우 쉬웠으나 그걸 js로 작업하는 것을 찾고 있었던 것..

 

방법은 매우 간단했다. 허무하게..

const maxIndex ='<%=maxIndex%>'
 
그렇다... 이게 끝
ejs파일 안에서는 <%= 받아온 데이터 변수%>가 불러오는 값이었지만 script에서 이 값을 불러오는 방법은 그저 '(따오표)로 감싸주는 것이었다.
반응형

'개발일지' 카테고리의 다른 글

쿼리 스트링  (0) 2022.11.08
multiple 속성(input)  (0) 2022.11.08
express에서 동적 경로 설정하기 (req.params)  (0) 2022.11.07
vsCode 확장팩 설치  (0) 2022.11.07
페이지네이션 구현하기  (0) 2022.11.07
Comments