LoginSignup
20

More than 5 years have passed since last update.

Backbone.jsのtemplateをgruntを使って外部ファイル化

Last updated at Posted at 2014-04-23

Backbone.js(だけじゃないけど)の特徴の一つはDOMをtemplateとして保持できること。
一方でhtmlファイル内のtemplateが増えすぎるとごちゃごちゃしてしまうし、複数人開発の場合にも支障が発生する。

今回はgruntのプラグインであるcontrib-jstを使って、複数のtemplateを、1つの外部ファイルにまとめてゆく。

contrib-jstのインストール

いつも通り、npmコマンドを使ってインストール。

cmd.exe
>npm install grunt-contrib-jst -save-dev

contrib-jstの設定

今回はこのようなディレクトリ構造を例にして説明してゆく。

+--jst // 外部ファイル化されたtemplateが置かれる場所
|
+--template // 元のtemplateのファイルの場所
|
+Gruntfile.js

Gruntfile.jsには以下のように記述(一例)。

Gruntfile.js
module.exports = function (grunt) {
    var pkg = grunt.file.readJSON('package.json');
    grunt.initConfig({
        jst: {
            options: {
                processName: function (filename) {
                    return filename.match(/templates\/(.+)\.tmpl$/)[1];
                },
                processContent: function (src) {
                    return src.replace(/(^\s+|\s+$)/gm, '');
                }
            },
            dev: {
                files: {
                    // 出力先、及びファイル名: [元ファイルのパターン。例では分かりやすくtmpl形式を対象としている]
                    'jst/template.js': ['templates/**/*.tmpl']
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-jst'); // プラグインの読み込み
    grunt.registerTask('build', ['jst']); // タスク登録
};

実際の利用

元となるtemplateファイルの用意

例として、以下の様なtemplateファイルを用意する。
(Gruntfile.jsでもコメントしたが、分かりやすくするためtmpl形式としている)

template.tmpl
<li>listName <%- listName -></li>

ここでは通常のBackbone.jsのtempalteのように、htmlタグを<script type="text/template"></script>で括る必要はない。

外部ファイル生成

先ほど用意したGruntfile.jsでのタスク名(build)をコマンドラインで呼び出す。

cmd.exe
>grunt build
Running "jst:dev" (jst) task
File jst/template.js created.

Done, without errors.

設定した通り、jstディレクトリにtemplate.jsファイルが生成されていることを確認する。

生成されたtemplate.jsを利用する

templateを使いたいhtmlファイルに、template.jsを読み込ませる。

example.html
<script src="js/template.js"></script>

そしてBackbone.jsのViewでは、

exampleView.js
var exampleView = Backbone.View.Extend({
    template: JST['template'] // 元のファイル名から拡張子を省いたもの
});

このように呼び出せば利用することが出来る。
とっても楽ちん。楽しい✌('ω'✌ )三✌('ω')✌三( ✌'ω')✌

突っ込みどころ、盛大に間違っている部分等ありましたら是非ご指摘ください。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20