9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptのテンプレートエンジンはHandlebars.jsが最強なんじゃないか説

Last updated at Posted at 2018-08-31

ReactやAngularを導入するまでもないような、小規模のWebシステムをチャチャッと作る時、Handlebars.jsを使ったら便利過ぎたのでメモ。

Handlebars.js: Minimal Templating on Steroids

Handlebars.js に出会う前の私

APIから受け取ったデータでHTMLを組み立てる際、こんなことをしていました…。

JavaScript
function createHTML(data) {
    var html = '<ul>';
    for (var i=0; i<data.items.length; i++) {
        html+= '<li>' + data.items[i].name + '</li>';
    }
    html+= '</ul>';

    return html;
}

これはあくまで例なのでシンプルですが、実際はこんなもんじゃ済まないですよね。

Handlebars.js に出会ってからの私

HTML
<script type="text/x-handlebars-template" id="template">
  <ul>
    {{#each items}}
    <li>{{name}}</li>
    {{/each}}
  </ul>
</script>
JavaScript
var source = $('#template').html();
var template = Handlebars.compile(source);
var values = data;
var html = template(values);

これなら複雑なHTMLにも対応できますね!
記法もLaravelのBladeに似ているので、ララベラーの方も導入しやすいんじゃないでしょうか。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?