html문서를 좀더 편리하게 작성하게 도와줌.
nodeJS에서 뷰엔진으로 유명한건 EJS,PUG .. 등이있고.
갹 뷰엔진이 요구하는 문법에 따라 코드작성을 하면 뷰엔진이 자동으로 html파일로 렌더링해준다.
=> response를 html문서로 하려고할때 html을 그때그때 짠다고 생각해보면.. 어우..
원하는 key,value로 데이터를 할당할수 있게 해줌.
하지만 몇몇 key name들은 서버의 행동을 설계하기위해 사용된다.
=> 목록은 https://expressjs.com/ko/4x/api.html#app.settings.table
말그대로 사용할 view engine을 세팅하는 프로퍼티.
app.set('view engine','pug') //pug 뷰엔진 사용
view들이 담긴 경로를 지정해주는 프로퍼티. => view는 뷰엔진으로 작성한 문서들이 될거다
app.set('views',process.cwd()+'/src/views/');
View를 렌더링하고 렌더된 html문자열을 client에 보냄.
res.render(view, [data],[callback])
인자를 하나씩 뜯어보자.
res.render('myView',{ name : 'Kim' },function (err, html) {
res.send(html)
})
대표적으로 많이쓰이는 nodejs 뷰엔진들중 하나.
doctype html
html(lang="ko")
head
link(rel="stylesheet" href="./style.css")
body
h2 hello World!
보면 알겠지만 element의 속성은 괄호() 안에 적는걸 볼수있다.
// partials
footer © #{new Date().getFullYear()} Footer
// 사용
include 경로/partials.pug
pug문을 불러와서 붙이는 느낌이다. footer나 반복이 필요한 녀석들을 partials로 짜서 반복의 최소화를 하는게 좋을것같다.
=> 보면 알겠지만 #{} 안에 JS코드를 넣어줄수있다.
// mixins
mixin mymix(info)
div
h4 #{info.title}
ul
li #{info.content} is content
li #{info.month} is month
// 사용 in base.pug
include 경로/mymix.pug (pug확장자는 지워도 무방하다)
h1
+mymix(data)
//controllers
res.send("base",{title:'test',content:"content",month:3}
=> mixins는 리액트의 컴포넌트같은 느낌이든다.
// base.pug
head
block title
body
block content
// main.pug
extends base.pug //base.pug의 기본적인 틀을 상속후 추가작업
block title
title myTitle
block content
h1 my Content
+mymix(data)
div
h1 conditional
ul
if #{boolean} => 컨트롤러에서 넘어온 data를 활용해도 되겠지?
li it's true
else
li it's false
마찬가지로 컨트롤러부분에서 넘어온 지역변수를 활용할수도 있을것이다.
ul
each item,index in ['first','second','third']
li #{`${item} #${index}`}
else
li is empty!
기본적인 css를 입혀주는 미들웨어.
미들웨어는 response하기전 중간단계 느낌이라고 했으니.
html문서를 응답한다고 생각하면 응답하기전에 css를 입혀주고 응답을 리턴하게 도와주는 녀석. 이라고 이해하면 될것이다.
=> 개발단계에서 어느정도 디자인이 된상태로 개발하고싶을때 이용하면 좋겠다.