LoginSignup
3
3

More than 5 years have passed since last update.

JSテンプレートエンジン handlebars プリコンパイルまで

Posted at

JSテンプレートエンジン Handlebars 導入時メモ

Grunt

プリコンパイル用
$ npm i --save-dev grunt-contrib-handlebars

concat用
$ npm i --save-dev grunt-contrib-concat

handlebarsテンプレートエンジン

handlebars v4.0.5
Handlebars-Helpers

how to

.hbs -> .html -> .js

[1] foo.hbs

---
# 出力htmlテンプレート
---

{{!-- helper使う場合 [helper関数 引数] --}}
<h1>\{{ helper-hoge bar }}</h1>

{{!-- object使う場合 --}}
<ul>
    \{{# each fruitGroups }}
    <li>\{{ . }}</li>
    \{{/ each }}
</ul>

[2] foo.html

// Gruntifle.js
assemble: {
    template: {
        files: [
           {
               expand: true,
               cwd: 'somedir1/',
               src: '*.hbs',
               dest: 'somedir2/'
           }
        ]
    }
}
$ grunt assemble:template
// html
<h1>something title</h1>
<ul>
    <li>りんご</li>
    <li>バナナ</li>
    <li>メロン</li>
</ul>

[3] foo.js

// Gruntifle.js
compile: {
    build: {
        options: {
            namespace: "NAMESPACE.Templates",
            processName: function(filename){
                return (/\/([a-zA-Z1-9-]+)\.html$/.exec(filename))[1];
            }
        },
        files: {
            'somedir3/template.js': ['somedir2/template.html']
        }
    }
}
# grunt compile
// js
this["NAMESPACE"] = this["NAMESPACE"] || {};
this["NAMESPACE"]["Templates"] = this["NAMESPACE"]["Templates"] || {};

this["NAMESPACE"]["Templates"]["foo"] = Handlebars.template({
・
・
・
});

実装

script.js

(function($, NAMESPACE){

   compile: function (object) {
        NAMESPACE.Templates.foo(object);
   },

   render: function (object) {
        var htmlStrings =this.compile(object);

        $('#some-elem').append(htmlStrings);
   }

})(jQuery, window.NAMESPACE = window.NAMESPACE || {});

[注意]IE8以下ブラウザの場合

handlebarsはIE6以降サポートをしていますが、Handlebars-Helpersは配列に対するindexOfを使っているためIE8以下でエラーになります。下記のように書き換えて対応しました。

eR.add('in', function(left, right) {
    if ( ! isArray(right)) {
        right = right.split(',');
    }
    for (var i = 0, max = right.length; i < max; i++) {
        console.log(right[i], left, right[i] === left);
        if (right[i] === left) {
            return true;
            break;
        }
    }
    return false;
});

Array.prototype.indexOf()

3
3
0

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
3
3