waffle
Version:
シンプルなWEBアプリケーションフレームワークです。(ALL YOUR NODE ARE BELONG TO US)
128 lines (114 loc) • 3.92 kB
JavaScript
/*
* Copyright 2012 Katsunori Koyanagi
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* @overview EJSを使用したレンダリング機能を提供するアドオンです。 具体的には<a
* href="https://github.com/visionmedia/ejs">EJS</a>を参照してください。
*/
;
var ejs = require("ejs");
/**
* EJSでのレンダリングを行うレンダラです。
* <p>
* このオブジェクトはレンダラとして利用可能ですが、関数として使用した場合は、EJSのオプションを定義することができます。
* このレンダラをコントローラで指定する場合のフォーマットは、<prefix:path>となります。例えば、ejsという名前でこのレンダラを登録した場合に、
* foo/bar.ejsを示す場合は、"ejs:foo/bar.ejs"となります。ただし、拡張子とプレフィックスが同一の場合はプレフィックスを省略することができますので、
* "foo/bar.ejs"と指定することも可能です。
* </p>
* <p>
* このモジュールで使用されるEJSモジュールは依存モジュールには含まれません。 必要な場合にコマンドで"npm install
* ejs"を実行してインストールする必要があります。
* </p>
*
* @example <code>
* var waffle = require("waffle");
* config.renderer.register("ejs", waffle.renderers.ejs({open : "<%=", close : "%>"}));//use option
* config.renderer.register("ejs", waffle.renderers.ejs);// use default
* </code>
*
* @function
* @name Renderers#ejs
*
* @param {Object}
* options
* @return {Object} レンダラ
*/
var renderer = module.exports = function(options) {
return {
render : createRenderer(options)
};
};
function createRenderer(defaultOptions) {
defaultOptions = defaultOptions || {};
var cache = {};
return function(context, param, data, callback) {
if (!context.app.isResourceInCache(param)) {
delete cache[param];
}
compile(param, cache, defaultOptions, context,
function(error, compiled) {
if (error) {
context.error(500, error);
return;
}
if (!compiled) {
callback();
return;
}
var options = {};
for ( var key in defaultOptions) {
options[key] = defaultOptions[key];
}
options.__proto__ = data;
var content;
try {
content = compiled.call(context, options);
} catch (e) {
context.error(500, e);
return;
}
var buf = new Buffer(content);
context.res.statusCode = 200;
context.res.setHeader("Content-Length", buf.length);
context.res.write(buf);
callback();
});
};
}
function compile(param, cache, defaultOptions, context, callback) {
if (param in cache) {
callback(null, cache[param]);
return;
}
context.app.getText(param, function(template) {
if (template == null) {
callback(null, null);
return;
}
var options = {};
for ( var key in defaultOptions) {
options[key] = defaultOptions[key];
}
options.filename = param;
try {
var compiled = ejs.compile(template, options);
cache[param] = compiled;
callback(null, compiled);
} catch (e) {
callback(e, null);
}
});
}
renderer.render = createRenderer(null);