ejs 모듈은 html 템플릿 생성을 위한 모듈이다.
jsp 와 비슷한 형태를 하고 있으며, jsp 의 스크립틀릿 형태로 작성하면
자체 렌더러를 이용하여 html 형식으로 변환해 준다.
var ejs = require('ejs');
var fs = require('fs');
// file read
html_str = fs.readFileSync(__dirname + '/sample.ejs', 'utf-8');
// compile
template = ejs.compile(html_str);
console.log(template({ 'title' : 'compile' }));
// render
console.log(ejs.render(html_str, { 'title' : 'render' }));
compile과 render 메소드를 이용하여 변환하면 된다.
아래는 sample.ejs 파일의 내용이다.
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= title %></h1>
<hr/>
<% for(var i = 0; i < 10; i++) { %>
<h2>2 * <%= i %> = <%= 2 * i%><h2>
<% } %>
</body>
</html>
ejs에서 <%= 변수명 %> 는 System.out.print() 와 같고
<% %> 는 스크립트릿을 이용할 수 있다.
즉 해당 내용 안에서는 제어문이나, 반복문을 사용하면 된다.
변환된 결과는 다음과 같다.
<html> <head> <title>compile</title> </head> <body> <h1>compile</h1> <hr/> <h2>2 * 0 = 0<h2> <h2>2 * 1 = 2<h2> <h2>2 * 2 = 4<h2> <h2>2 * 3 = 6<h2> <h2>2 * 4 = 8<h2> <h2>2 * 5 = 10<h2> <h2>2 * 6 = 12<h2> <h2>2 * 7 = 14<h2> <h2>2 * 8 = 16<h2> <h2>2 * 9 = 18<h2> </body> </html> <html> <head> <title>render</title> </head> <body> <h1>render</h1> <hr/> <h2>2 * 0 = 0<h2> <h2>2 * 1 = 2<h2> <h2>2 * 2 = 4<h2> <h2>2 * 3 = 6<h2> <h2>2 * 4 = 8<h2> <h2>2 * 5 = 10<h2> <h2>2 * 6 = 12<h2> <h2>2 * 7 = 14<h2> <h2>2 * 8 = 16<h2> <h2>2 * 9 = 18<h2> </body> </html>
반응형
'프레임워크 > [JS] node.js' 카테고리의 다른 글
| [nodejs][express] express 설치 및 기본 프로젝트 생성하기 (0) | 2016.03.30 |
|---|---|
| [jade] node.js용 html 템플릿 엔진 (0) | 2016.03.10 |
| [에러] possible EventEmitter memory leak detected. 에러 처리 (0) | 2016.02.18 |
| node.js와 mysql 연동하기 (0) | 2016.02.17 |
| node.js의 LTS 버전과 Stable 버전의 차이 (1) | 2016.01.27 |