elice/WIL
[week_06] Template Engine
๊ฑด๋ง๋
2022. 2. 18. 15:31
1. ํ ํ๋ฆฟ ์์ง
- ์๋ฒ์์ ํด๋ผ์ด์ธํธ๋ก ๋ณด๋ผ HTML์ ํํ๋ฅผ ๋ฏธ๋ฆฌ ํ ํ๋ฆฟ์ผ๋ก ์ ์ฅ
- ๋์ ์์ ๋ฏธ๋ฆฌ ์์ฑ๋ ํ ํ๋ฆฟ์ ๋ฐ์ดํฐ๋ฅผ ๋ฃ์ด์ ์์ฑ๋ HTML ์์ฑ
- ํ ํ๋ฆฟ ์์ฑ ๋ฌธ๋ฒ๊ณผ ์์ฑ๋ ํ ํ๋ฆฟ์ HTML๋ก ๋ณํํ๋ ๊ธฐ๋ฅ ์ ๊ณต
1-1. Express.js์ ํ ํ๋ฆฟ ์์ง
- EJS: html๊ณผ ์ ์ฌํ ๋ฌธ๋ฒ์ ํ ํ๋ฆฟ ์์ง
- Mustache: ๊ฐ๋จํ ๋ฐ์ดํฐ ์นํ ์ ๋๋ง ์ ๊ณตํ๋ ๊ฒฝ๋ํ๋ ํ ํ๋ฆฟ ์์ง
- Pug: ๋ค์ฌ์ฐ๊ธฐ ํํ์์ ์ด์ฉํ ๊ฐ๋ตํ ํ๊ธฐ์ ๋ ์ด์์ ๋ฑ ๊ฐ๋ ฅํ ๊ธฐ๋ฅ ์ ๊ณต
2. Pug
- ๋ค์ฌ์ฐ๊ธฐ ํํ์์ ์ด์ฉํด ๊ฐ๋ ์ฑ์ด ์ข๊ณ ๊ฐ๋ฐ ์์ฐ์ฑ์ด ๋์, HTML์ ์ ๋ชจ๋ฅด๋๋ผ๋ ๋ฌธ๋ฒ์ ์ค์๋ฅผ ์ค์ผ ์ ์์
- layout, include, mixin ๋ฑ ๊ฐ๋ ฅํ ๊ธฐ๋ฅ ์ ๊ณต
html
head
title= title
body
h1#greeting ์๋
ํ์ธ์
a.link(href="/") ํ์ผ๋ก
- HTML ๋ซ๊ธฐ ํ๊ทธ ์์ด ๋ค์ฌ์ฐ๊ธฐ๋ก ๋ธ๋ญ ๊ตฌ๋ถ
- = ์ ์ด์ฉํด์ ์ ๋ฌ๋ฐ์ ๋ณ์ ์ฌ์ฉ ๊ฐ๋ฅ
- id๋ class๋ ํ๊ทธ ๋ค์ ์ด์ด์ ๋ฐ๋ก ์ฌ์ฉ
- ( )์ ์ด์ฉํด์ attribute ์ฌ์ฉ
each item in arr
if item.name == 'new'
h1 New Document
else
h1 `${item.name}`
- each ~ in ํํ์์ผ๋ก ์ฃผ์ด์ง ๋ฐฐ์ด์ ๊ฐ์ ์ํํ๋ฉฐ HTML ํ๊ทธ๋ฅผ ๋ง๋ค ์ ์์
- if, else if, else๋ฅผ ์ด์ฉํด ์ฃผ์ด์ง ๊ฐ์ ์กฐ๊ฑด์ ํ์ธํ์ฌ HTML ํ๊ทธ๋ฅผ ๋ง๋ค ์ ์์
// layout.pug
html
head
title= title
body
block content
// main.pug
extends layout
block content
h1 Main Page
- block์ ํฌํจํ ํ ํ๋ฆฟ์ ์ ์ธํ๋ฉด ํด๋น ํ ํ๋ฆฟ์ layout์ผ๋ก ์ฌ์ฉํ ์ ์์
- layout์ extendsํ๋ฉด block ๋ถ๋ถ์ ์์ฑํ HTML ํ๊ทธ๊ฐ ํฌํจ๋จ
// title.pug
h1= title
// main.pug
extend layout
block content
include title
div.content
์๋
ํ์ธ์
pre
include article.txt
- ์์ฃผ ๋ฐ๋ณต๋๋ ๊ตฌ๋ฌธ์ ๋ฏธ๋ฆฌ ์์ฑํด๋๊ณ includeํ์ฌ ์ฌ์ฉ๋ ์ ์์
- ์ผ๋ฐ์ ์ธ ํ ์คํธ ํ์ผ๋ includeํ์ฌ ํ ํ๋ฆฟ์ ํฌํจ ๊ฐ๋ฅ
- layout์ ๋ฐ๊นฅ์ชฝ์ ํ์ ์ ์ธํ๊ณ ๊ฐ์ ธ๋ค ์ฐ๋ ๊ฒ
- include๋ ํ๋์ ์กฐ๊ฐ์ ๋ง๋ค์ด๋๊ณ ๊ฐ์ ธ๋ค ์ฐ๋ ๊ฒ
// listItem.pug
mixin listItem(title, name)
tr
td title
td name
// main.pug
include listItem
table
tbody
listItem('์ ๋ชฉ', '์ด๋ฆ')
- mixin์ ํ ํ๋ฆฟ์ ํจ์์ฒ๋ผ ์ฌ์ฉ ๊ฐ๋ฅ
- include๋ ๊ฐ์ ์ง์ ํ ์ ์์ง๋ง, mixin์ ํ๋ผ๋ฏธํฐ๋ฅผ ์ง์ ํ์ฌ ๊ฐ์ ๋๊ฒจ๋ฐ์ ํ ํ๋ฆฟ์ ์ฌ์ฉ ๊ฐ๋ฅ
3. Express.js์ pug์ ์ฐ๋
// app.js
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// request handler
res.render('main', {title: 'Hello Express'});
- app.set์ ์ด์ฉํด ํ ํ๋ฆฟ์ด ์ ์ฅ๋๋ ๋๋ ํฐ๋ฆฌ('views') ์ง์
- ์ด๋ค ํ ํ๋ฆฟ ์์ง์ ์ฌ์ฉํ ์ง ์ง์ ('view engine', 'pug')
- res.render ํจ์๋ app.set์ ์ง์ ๋ ๊ฐ์ ์ด์ฉํด ํ๋ฉด์ ๊ทธ๋ฆฌ๋ ๊ธฐ๋ฅ
- render ํจ์์ ์ฒซ ๋ฒ์งธ ์ธ์๋ ํ ํ๋ฆฟ์ ์ด๋ฆ
- render ํจ์์ ๋ ๋ฒ์งธ ์ธ์๋ ํ ํ๋ฆฟ์ ์ ๋ฌ๋๋ ๊ฐ
3-1. Express.js์ app.locals
// app.js
app.locals.appName = "Express"
// main.pug
h1= appName // <h1>Express<h1>
- Express.js์ app.locals๋ฅผ ์ฌ์ฉํ๋ฉด render ํจ์์ ์ ๋ฌ๋์ง ์์ ๊ฐ์ด๋ ํจ์๋ฅผ ์ฌ์ฉํ ์ ์์
- ํ ํ๋ฆฟ์ ์ ์ญ์ผ๋ก ์ฌ์ฉ๋ ๊ฐ์ ์ง์ ํ๋ ์ญํ
3-2. express-generator ์ฌ์ฉ ์ ํ ํ๋ฆฟ ์์ง ์ง์ ํ๊ธฐ
$ express --view=pug myapp