mojito 是 Yahoo 推出的 NodeJS MVC Framework,
前一陣子在下跟同事分別有在 OSDC.tw 跟 JSDC.tw 分享過 mojito 的概念,
另外我還到 Nodejs Taiwan Party 的活動中分享過。
有興趣的朋友可能參考PS中的相關連結。
最近 柯南發現 Mojito 的版本已經爬到 0.3.26 了,
雖然 YUI 核心看起來仍在 3.4.1 ,
不過 mojito 的擴充性隨著版本越來越前進,
也越來越進步了。
今天和大家分享如何擴充 view template engine:
mojito 的 view template engine,
最早的版本只支援 mustache ,
http://mustache.github.com/
雖然我這陣子用下來覺得不錯用,
但是每個開發者與團隊總有偏好,
所以透過以下幾個步驟,
mojito 也可以使用其他的 view engine。
以下用 handlebars 為例。
1. 到 packages.json 中的 dependencies 新增 handlebars 的設定:
ex:
"dependencies": {
...
"handlebars": ">= 1.0"
}
2. 在命令列中 npm i . 安裝之。
3. 在 mojito app的第一層目錄新增 addons/view--engines/hb.server.js 的檔案
並加入以下內容
YUI.add('addons-viewengine-hb', function(Y, NAME) {
var hb = YUI.require(__dirname + '/../../node_modules/handlebars'),
fs = require('fs');
/**
* Class text.
* @class HandleBars
* @private
*/
function HbAdapter(viewId) {
this.viewId = viewId;
}
HbAdapter.prototype = {
/**
* Renders the Handlebars template using the data provided.
* @method render
* @param {object} data The data to render.
* @param {string} mojitType The name of the mojit type.
* @param {string} tmpl The name of the template to render.
* @param {object} adapter The output adapter to use.
* @param {object} meta Optional metadata.
* @param {boolean} more Whether there will be more content later.
*/
render: function(data, mojitType, tmpl, adapter, meta, more) {
var me = this;
Y.log('Rendering template "' + tmpl + '"', 'mojito', NAME);
try {
var template = hb.compile(this.compiler(tmpl));
var result = template(data);
console.log(result);
} catch(e){
Y.log(e);
}
adapter.flush(result,meta);
if(!more) {
adapter.done('',meta);
}
},
compiler: function(tmpl) {
return fs.readFileSync(tmpl, 'utf8');
}
};
Y.namespace('mojito.addons.viewEngines').hb = HbAdapter;
}, '0.1.0', {requires: []});
4. 在 mojito 中 mojit 的 controller.server.js 中直接將資料傳給 view
ex:
added_ve: function(ac) {
ac.done({
"title": "Handlebars at work!",
"view_engines": [ "Mustache","EJS","Jade", "dust","underscore" ],
"ul": { "title": 'Here are some of the other available rendering engines:' }
});
},
5. 在 mojit/views 中新建對應的 added_Ve.hb.html
<h2>{{title}}</h2>
<div id="{{mojit_view_id}}">
{{#with ul}}
<h3>{{title}}</h3>
{{/with}}
<ul>
{{#each view_engines}}
<li>{{this}}</li>
{{/each}}
</ul>
</div>
6. 執行 mojito start,當我們連到 該 頁面就會發現該頁面會用 handlebars rendering 頁面了!
PS1: 參考資料 http://developer.yahoo.com/cocktails/mojito/docs/topics/mojito_extensions.html#view-engines
PS2: OSDC.tw http://cire.pixnet.net/blog/post/37300934
PS3: JSDC.tw http://davidshariff.com/blog/yahoo-mojitio-jsdc-tw/
PS4: NodeJS Taiwan Party https://speakerdeck.com/u/ddsakura/p/mojito-and-cocktails
Technorati Tags: mojito, nodejs, view engines, extend