Node.js(6) - 템플릿 엔진
템플릿 엔진
- React, Vue, Angular 주로 사용하긴 하지만 보통 같이 쓰이긴 함
- 반복문, 조건문, 변수 사용 가능
- html 기능을 확장해줌(반복문, 조건문, 변수 사용할 수 있도록 함)
Pug
app.js
res.render에서 두 번째 인수 객체에 Pug 변수를 넣는다.
router/index.js
router.get('/', function(req, res, next){
res.render('index', {title : 'Express'});
});
// 이렇게 하는 것도 가능함 : res.locals 객체에 넣어서 미들웨어간에 공유될 수 있도록 하기
router.get('/', function(req, res,next){
res.locals.title = 'Express';
res.render('index');
});
})
index.pug
h1 = title
p Welcome to #{title}
button(class=title, type = 'submit') 전송
input(placeholder= title + '연습')
퍼그 안에서 자바스크립트 사용하기
이스케이프
for in이나 each in으로 반복문을 돌릴 수 있다.
값과 인덱스를 가져올 수 있음
퍼그 안에 다른 퍼그 파일을 넣을 수 있다.
- 헤더, 푸터, 네비게이션 파일을 따로따로 만들어서 재사용될 수 있기 때문에 공통 부분을 따로 관리할 수 있음
- include로 파일 경로를 지정해준다.
넌적스
- 확장자는 html 혹은 njk로 해줘야 한다.
넌적스 라이브러리 설치하기
npm i nunjucks
app.js 수정
...
const path = require('path');
const nunjucks = require('nunjucks');
dotenv.config();
const indexFouter = require('./routes');
const userRouter = require('./routes/user');
const app =express();
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'njk');
nunjucks.configure('views', {
express : app,
watch : true,
});
app.use(morgan('dev'));
...
변수
<h1>{{title}}</h1>
<p>Welcome to {{title}}</p>
<button class="{{title}}" type="submit">전송</button>
<input placeholder="{{title}} 연습" />
내부 변수 선언
- {%set 자바스크립트 구문}
이스케이프
배열 구문 작성하기
- {% %} 안에 for in 작성하기
loop.index
- for문 안에서는 1,2,3,4,5로 자동으로 나와준다.
- index를 따로 선언해줄 필요가 없음
{% if %} 안에 조건문 작성하기
레이아웃 지정하기
layout.html
<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
<link rel = "stylesheet" href="/style.css" />
{% block style %}
{% endblock %}
</head>
<body>
<header>헤더입니다.</header>
{% block content %}
{% endblock %}
</body>
</html>
body.html
{% extends 'layout.html' %}
{% block content %}
<main>
<p>내용입니다.</p>
</main>
{% endblock %}
{% block script %}
<script src= "/main.js"></script>
{% endblock %}
에러 처리 미들웨어
- 에러 발생할 때 템플릿 엔진과 상관없이 템플릿 엔진 변수를 설정하고 error 템플릿을 렌더링한다.
- process.env.NODE_ENV는 개발 환경인지 배포 환경인지 구분해주는 속성이다.
app.js
...
app.use((req, res, next) => {
const error = new Error('${req.method} ${req.url} 라우터가 없습니다.');
error.status = 404;
next(error);
});
app.use((err, req, res, next) => {
res.locals.message = err.message ;
res.locals.error = process.env.NODE_ENV !== 'production' ? err : {};
res.status(err.status || 500);
res.render('error');
});
...