Node.js/Express Pug(view engine)-1
04 May 2021Pug는 Node Express Template Engine이다.
☄ Pug 설치
const app = express();
app.set("view engine", "pug");
npm install pugapp.set("view engine", "pug");
위 코드는 Express에게 pug를 view engine으로 사용하겠다는 설정이다.
참고: 템플릿 엔진으로 pug 설정 → app.set()
pug를 사용하면 javascript로 html을 생성할 수 있으며, html을 훨씬 편하게 작성할 수 있다.

https://pugjs.org/language/tags.html
☄ Pug로 간단하게 html 생성하기(기초)
- 태그 생성 시,
<>없이 태그 명만 쓰면 됨 - 자식 태그는 부모 태그 라인 밑에
taporwhite space로 시작하면 됨 - 태그 내 텍스트 작성은 태그 다음
=orwhite space다음 작성 - 속성은 태그 명 옆에 함수처럼
()를 쓰고 안에attribute='value'형식으로 작성 class는tag.classid는tag#iddiv는 태그 명div를 생략하고.class처럼 클래스 명만 입력해도 됨- 기본적으로
doctype html(소문자로 작성)→<!DOCTYPE html>
pug 사용 예시
// Pug로 작성(플러그인이 없어서 이쁘게 안보임..)
doctype html
ul
li Item A
li Item B
li Item C
div.row
div#content
.column
p='hi hi'
input(type='checkbox' checked)
<!-- html로 변환 -->
<!DOCTYPE html>
<ul>
<li>Item A</li>
<li>Item B</li>
<li>Item C</li>
</ul>
<div class="row"></div>
<div id="content"></div>
<div class="column"></div>
<p>hi hi</p>
<input type="checkbox" checked />
☄ pug 파일 렌더링
/* 디렉토리 구조
├──node_modules
├─┬src
│ ├─┬controllers
│ │ ├──userController.js
│ │ └──videoController.js
│ ├─┬routers
│ │ ├──globalRouter.js
│ │ ├──userRouter.js
│ │ └──videoRouter.js
│ └─┬views <--------------추가
│ └──home.pug
├──server.js
└──pakage.json
*/
<!-- home.pug -->
doctype html
html(lang="ko")
head
title Wetube
body
h1 Welcome to Wetube
footer © 2021 Wetube
위와 같이 작성한 뒤, /으로 들어오는 요청에 대한 응답으로 home.pug를 내보내면 된다.
이때 res.render() 함수를 사용해 html로 렌더링 된 문서로 클라이언트에게 응답할 수 있다.
export const trending = (req, res) => res.render("home");
특별히 경로를 지정해 주지 않아도 되는 이유는 express가 스스로 디렉토리 안에서 views 파일들을 찾아 렌더링 시켜주기 때문이다.
default 설정으로 express는 모든 views(ex. .pug파일들)을 렌더링 할 때 cwd(current working directory) + /views 폴더 내에서 검색하는데 이를 views 설정이라고 한다.
cwd는 Node가 시작되는 위치로 package.json 파일이 있는 위치라고 생각하면 된다.

A directory or an array of directories for the application’s views. If an array, the views are looked up in the order they occur in the array.
- type →
StringorArray - default →
process.cwd() + '/views'
하지만 위와 같이 디렉토리를 구성하고 /경로로 접속해 보면 에러가 뜬다.

위에 디렉토리 구조를 자세히 보면 모든 코드를 src 폴더 안에 넣어 놨고, views 역시 src 폴더 안에 들어가 있다. 따라서 pakage.json이 위치한 cwd는 src 밖의 폴더이므로 express가 views directory를 찾을 수 없다는 에러가 발생한다.
이를 해결하기 위해서는 views 설정에서 default directory를 바꿔줘야 한다.
참고: 템플릿 엔진으로 pug 설정 → app.set()
app.set("views", process.cwd() + "/src/views");
