2013년 6월 11일 화요일

express - template engine integration (app.engine)

0. express에서 template engine을 사용하기 위해서 app.engine()를 사용한다.

1. 그러기 위해서 jade, ejs module 등이 아래와 같이 특정 함수를 export해 줘야 한다. 그래야 express가 rendering을 제대로 할 수 있다. 아래는 express가 2.x에서 3.x로 업그레이드 되면서 바뀐 함수 signature다.
Express 2x template engine compatibility required the following module export:
exports.compile = function(templateString, options) {
  return a Function;
};
Express 3x template engines should export the following:
exports.__express = function(filename, options, callback) {
  callback(err, string);
};
2. 이걸 구현 안 한 module은 ? 이런식으로 사용한다.
var markdown = require('some-markdown-library');

app.engine('md', function(path, options, fn){
  fs.readFile(path, 'utf8', function(err, str){
    if (err) return fn(err);
    str = markdown.parse(str).toString();
    fn(null, str);
  });
});
3. 그럼 이건 먼가?
app.engine('html', require('ejs').renderFile);
In this case EJS provides a .renderFile() method with the same signature that Express expects: (path, options, callback), though note that it aliases this method as ejs.__express internally so if you're using ".ejs" extensions you dont need to do anything.
- renderFile 함수 열어 보면 signature가 __express와 같음을 알 수 있다.


4. express 3.x 현재 버전에서 ejs module로는 template을 사용할 수 없다. (못 찾은 건지..) ejs-locals module을 사용한다. (아시는 분 계시면 댓글 좀 달아주세요.)

댓글 없음:

댓글 쓰기