본문 바로가기
JavaScript

Variables in Pug

by ma_ro 2020. 2. 24.

res.locals ( https://expressjs.com/ko/4x/api.html#res.locals )

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

req/res 응답 주기에서 해당 주기의 res 로컬 변수를 전역 변수처럼 사용하게 해주는 메서드.

 

app.use(function (req, res, next) {
  res.locals.user = req.user
  res.locals.authenticated = !req.user.anonymous
  next()
})

여기서 req의 user 변수를 locals에 담아서 다른 곳에서도 user 변수를 사용할 수 있도록 한다.

미들웨어함수로 사용하면 모든 요청에서 해당 메서드가 실행되므로 지역 변수를 전역 변수처럼 사용할 수 있게 된다.

 

const localsMiddleware = (req, res, next) => {
    res.locals.siteName = "WeTube";
    res.locals.routes = routes;
    next();
}

이런 식으로 만들어서 미들웨어 함수로 사용하면 siteName이라는 변수와 routes라는 객체를 다른 곳에서도 사용할 수 있다.

 

title | #{siteName}
a(href=routes.join) Join

pug에서는 이런 식으로 불러와서 사용한다.

 

 

res.render ( https://expressjs.com/ko/4x/api.html#res.render )

res.render(view [, locals] [, callback])

Renders a view and sends the rendered HTML string to the client. Optional parameters:

  • locals, an object whose properties define local variables for the view.
  • callback, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes next(err) internally.

첫 번째 파라미터는 랜더링할 view 이고, 다음 파라미터는 view 로 전달할 지역변수이다. 이걸 이용하여 pug에서 특정 템플릿에 원하는 변수를 전달 할 수 있다.

'JavaScript' 카테고리의 다른 글

MongoDB with node.js  (0) 2020.03.03
Express 404처리  (0) 2020.03.02
Pug Partial  (0) 2020.02.24
Pug 레이아웃  (0) 2020.02.24
Pug 설치편  (0) 2020.02.24

댓글