LoginSignup
8
6

More than 5 years have passed since last update.

hogan.jsの基本的な使い方まとめ

Posted at

そもそもHogan.jsって?

Twitter社から出たApache Licenseのjava scriptのテンプレートエンジン

https://github.com/twitter/hogan.js
http://twitter.github.io/hogan.js/

対象version

Hogan.js 3.0.2

Hogan.jsの基本的知識

  • Mustacheというテンプレートエンジンの構文に則っている
  • 複雑な制御文が書けないのでロジックとviewがほぼ分離される
  • 事前にコンパイルもできるっぽい
  • そのままライブラリを読み込んで、利用もできる
  • 他ライブラリの依存はない(standalone)
  • 自動でエスケープされる
  • テストはQunitmastache spec
  • バージョンはSemantic Versioningに則り管理されている様子。詳しくはこちら

Hogan.js(=Mustache)の基本的構文

変数

{{}}で囲む
{{name}}
nameという変数名が出力される

変数のアンエスケープ

{{{}}}で囲む
{{{name}}}
nameという変数にhtmlタグが混在していてhtmlタグを有効にして出力したい場合に使う

条件分岐

  • conditionがtrueの場合
 {{#condition}}
  output
 {{/condition}}
  • conditionがfalseの場合
 {{^condition}}
  output
 {{/condition}}

ループ

if true文と同じになるが配列が渡った際はループとして動作する

$array = array(
  array('name' => 'aaa'),
  array('name'  => 'bbb')
)
--
{{#array}}
 {{name}}
{{/array}}

Lambda

説明が難しいので

Template:

{{#wrapped}}
 {{name}} is awesome.
{{/wrapped}}
Hash:

{
 "name": "Willy",
 "wrapped": function() {
   return function(text, render) {
     return "<b>" + render(text) + "</b>"
   }
 }
}

参照:https://mustache.github.io/mustache.5.html

コメント

!をつける
{{! name}}

気づいた点

  • Mustacheは訳すと口ひげ。だから{を多用しているっぽい
  • Semantic Versioningの日本語版をこの機会によく読めてよかった
  • 同様のhandlebarsjsあたりもちょっと見てみたくなった
8
6
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
8
6