Backbone.jsのテンプレートにHandlebarを使います。
ただ、Handlebarで問題となるのがコンパイル前の遅さ。
それを補うために、Gruntを使ってプリコンパイルする手法があります。
そのためには.hbsという拡張子でテンプレートファイルを作成して、この内容をgrantを使いtemplate.jsに随時反映させるのが便利です。
先ずはGruntの設定。
Gruntについてはこちら。
Grunt.js
コマンドを開き、作業ディレクトリまで進みます。
cd /yourapps/dir/
イニシャライズを行います。
npm init
これでpackage.jsonが生成されました。
次にgruntをインストールします。
npm install grunt --save-dev
これでnode_modulesというフォルダが生成されました。
次に、プラグインを入れてみます。
package.jsonを編集します。
プラグインはgrunt-contribを使ってみます。
grunt-contribについての詳しい説明はこちら。
grunt-contrib
今回はhandlebarの自動プリコンパイルが目的ですが、それ以外にもcssやjsの圧縮など、便利な機能がたくさんあります。
少し時間がかかるかも知れませんが、一気に入れるには以下のコマンドを実行します。
npm install grunt-contrib --save-dev
個別に入れる場合は、
npm install grunt-contrib-handlebars --save-dev
や、
npm install grunt-contrib-watch --save-dev
このようにします。
使いなれて、好きなものだけ入れるためには、package.jsonを使うのが便利です。
一度、node_modulesのフォルダを削除します。
そして、devDependencies の項目に、
"devDependencies": {
"grunt": "~0.4.1",
"grunt-contrib-watch": "~0.3.1",
"grunt-contrib-cssmin": "~0.4.2"
}
この様に必要なものだけ記述しておきます。
そして、以下のコマンドを実行します。
npm install
Gruntfile.js
次に、Gruntfile.jsを設置します。
package.jsonと同じ階層に、Gruntfile.jsを作成します。
このファイルには、以下の記述を追加します。
module.exports = function(grunt) {
grunt.initConfig({
handlebars: {
compile: {
options: {
namespace: "MyApp.Templates",
processName: function(filepath) { // input -> app/hbs/partial.hbs
var pieces = filepath.split("/");
return pieces[pieces.length - 1].replace(/.hbs$/ , ''); //output -> partial
}
},
files: {
"app/js/template.js": "app/hbs/*.hbs"
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-handlebars');
// Default task(s).
grunt.registerTask('default', ['handlebars']);
};
上の記述では、grunt.loadNpmTasks() でgrunt-contrib-handlebarsのプラグインを読み込み、
grunt.initConfig()内の記述がプラグインのセッティングになります。
そして、grunt.registerTask()でセッティングをプラグインに適用させている感じです。
セッティングについて簡単に説明すると、
namespace: テンプレートを呼び出す際の関数
processName: namespace オブジェクトに格納されたテンプレート関数を取り出すキー。上の記述では、デフォルトで
var tmpl = MyApp.Templates[‘app/hbs/partial.hbs’];
このようになっているのを、以下の様に呼び出せるための関数を記述しています。
var tmpl = MyApp.Templates.partial;
この状態で、
grunt
と実行すると、hbsファイルの変更がtemplate.js反映されます。
実際に.hbsファイルを作ってみます。
sample.hbs
{{#each this}}
{{/each}}
viewファイル
MyApp.Views.sample = Backbone.View.extend({
tmpl: MyApp.Templates.sample,
//some...
render: function() {
var json = this.model.toJSON();
var html = this.tmpl(json);
this.$el.html(html);
},
これで完成です。
以下を参考にさせて頂きました。ありがとうございます!
http://blog.mitsuruog.info/2013/03/backbonejshandlebarjs.html
http://kojika17.com/2013/03/grunt.js-memo.html
http://be-hase.com/javascript/248/