250x250
Notice
Recent Posts
Recent Comments
- Today
- Total
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- moment
- https
- css
- Node.js
- jsonwebtoken
- Find
- single quote
- clipBehavior
- wil
- certbot
- atlas
- flutter
- MYSQL
- TypeScript
- EC2
- Express
- findByIdAndDelete
- til
- await
- nginx
- sequelize
- mongodb
- AWS
- RDS
- double quote
- JavaScript
- Nodejs
- async
- TailwindCSS
- mongoose
Link
Archives
기억 휘발 방지소
[Node.js] Pug 설치 및 사용 본문
728x90
반응형
html을 브라우저로 리턴해주는 방법은 2가지 방법이 있다.
- res.send("<!DOCTYPE html><html lang="ko"><head><title>Title</title></head></body><body></html>")처럼 html코드를 적어서 리턴
- res.render("파일이름")으로 html파일자체를 리턴
첫 번째 방법은 html이 간단하면 괜찮은데 길어지면 코드 자체가 너무 길어지고 재사용하기도 힘들다.
그래서 두 번째 방법으로 하는게 낫다.
pug라는 템플릿 엔진을 사용해서 html을 작성해보려고한다.
📌 Pug
pug는 html의 '<'와 '>'를 없애고 최대한 간결한 키워드를 사용하는 것이 장점이다.
파이썬처럼 들여쓰기를 하여 계층구조를 구분한다.
또한 #{...}으로 변수명이나 JS코드를 입력해서 사용할 수도 있다.
doctype html
html(lang="en")
head
title= pageTitle
script(type='text/javascript').
if (foo) bar(1 + 5)
body
h1 Pug - node template engine
#container.col
if youAreUsingPug
p You are amazing
else
p Get on it!
p.
Pug is a terse and simple templating language with a
strong focus on performance and powerful features.
이렇게 작성하고 이렇게 생긴 코드를
<!DOCTYPE html>
<html lang="en">
<head>
<title>Pug</title>
<script type="text/javascript">
if (foo) bar(1 + 5)
</script>
</head>
<body>
<h1>Pug - node template engine</h1>
<div id="container" class="col">
<p>You are amazing</p>
<p>Pug is a terse and simple templating language with a strong focus on performance and powerful features.</p>
</div>
</body>
</html>
이렇게 바꿔준다.
📌 pug 사용하기
먼저, npm i pug로 pug 설치를 한다.
express 문서에 app.set을 보면 Property에 view engine이라는 것이 있다.
app.set("view engine", "pug");으로 뷰 엔진을 설정해준다.
import express from "express";
...
const app = express();
...
app.set("view engine", "pug");
...
그리고 라우터의 응답을 보내주는 곳에서 아래처럼 작성하면 home.pug파일을 읽어서 브라우저로 보내준다.
res.render는 매개변수로 뷰의 이름과 템플릿에 보낼 변수(객체형식)이다. 여기서 변수는 사용하지 않으므로 적지않았음.
const home = (req, res) => {
return res.render("home");
};
기본적으로 views폴더를 찾아서 그 안에 있는 파일을 찾아 보내주는데 경로를 변경하고 싶거나 다른 폴더에서 뷰 파일을 찾으려면 아래처럼 해주면 경로를 바꿀 수 있다.
'views'는 문서에 기본값이 process.cwd() + '/views'로 되어 있다. 내가 원하는 경로로 바꿔도 된다.
app.set("views", "경로");
아래처럼 작성하면 현재 디렉토리에서 views폴더를 의미한다.
app.set("views", path.join(__dirname, "views"));
728x90
반응형
'Web > Node.js' 카테고리의 다른 글
[Node.js] mongoDB를 연결해보자 (0) | 2021.09.17 |
---|---|
[Node.js] express.urlencoded는 뭘까? (0) | 2021.09.16 |
[Node.js] Router 사용하기 (0) | 2021.09.15 |
[Node.js] Middleware (0) | 2021.09.14 |
[Node.js] express.static (0) | 2021.09.09 |