(・w・) (・w・) (・w・)

“Mustache”というのは口ひげを指す言葉で、「ますたっしゅ」とか発音する様です。
テンプレートタグに使用されている「{」が口ひげに似てるので、そこらへんが由来っぽいです。

どこでも活躍できるテンプレートエンジン「Mustache」 | Mach3.laBlog

(・w・)っ mustache - Google 検索

いろんな言語でライブラリが作られてたり。

Logic-less templates.

Available in Ruby, JavaScript, Python, Erlang, PHP, Perl, Objective-C, Java, .NET, Android, C++, Go, Lua, ooc, ActionScript, ColdFusion, Scala, Clojure, Fantom, CoffeeScript, D, and for node.js.

Works great with TextMate, Vim, Emacs, and Coda.

The Manual: mustache(5) and mustache(1)

{{ mustache }}

ちなみに、デフォルトでHTMLエスケープする仕様らしい。

All variables are HTML escaped by default. If you want to return unescaped HTML, use the triple mustache: {{{name}}}.

mustache(5) -- Logic-less templates.

とりあえず、Rubyで使ってみる。
Ruby用のライブラリはこれ (・w・)っ defunkt/mustache - GitHub

MacBook Air に RubyGems でインストール可能。


$ sudo gem install mustache

今回は github からダウンロードして使ってみる。
最新ファイル群をダウンロード。


$ git clone --depth 1 git://github.com/defunkt/mustache

ちなみに最後にスラッシュつけて、


$ git clone --depth 1 git://github.com/defunkt/mustache/

ってやったら "is not a valid repository name" って怒られた。

ダウンロードしたファイル群の mustache/examples ディレクトリにサンプルあり。
simple.rb と simple.mustache を使ったサンプルがシンプルなので最初に見るのに良さそう。


$ ruby ./mustache/examples/simple.rb

Mustache#render がテンプレートをデータで埋めたテキストを String で返す。

よくわからないので、Ruby のハッシュと Array はどんなふうにテンプレートに埋め込めるのか試してみた。とくにネストしたところとか。

ハッシュと配列とシンボルとキーみたいなオブジェクトを生成して Mustache テンプレートに埋め込むサンプル。


$ cat ./hasharray.rb
$LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib'
require 'mustache'
 
class D
  def initialize(h, a, ah)
    @h = h
    @a = a
    @ah = ah
  end
  def hoge
    'data hoge'
  end
  attr_accessor :h, :a, :ah
end
 
class Sample < Mustache
  def initialize(d)
    @d = d
  end
  def hoge
    'sample hoge'
  end
  attr_accessor :d
end
 
# test data
h = {
  :symb  => 'symbhoge',
  'name' => 'namehoge'
}
a = [ 'item1', 'item2' ]
ah = [
  { 'x' => '1x', 'y' => '1y' },
  { 'x' => '2x', 'y' => '2y' }
]
 
d = D.new(h, a, ah)
s = Sample.new(d)
s.template_file = 'hasharray.txt'
puts s.render

次はテンプレートファイル。


$ cat ./hasharray.txt
d: {{d}}
d.h: {{d.h}}
d.h.symb: {{d.h.symb}}
d.h.name: {{d.h.name}}
d.a: {{d.a}}
#d.a:
{{#d.a}}
{{.}}
{{/d.a}}
/d.a:
d.ah: {{d.ah}}
#d.ah:
{{#d.ah}}
{{.}}
{{/d.ah}}
/d.ah:
#d.ah:
{{#d.ah}}
  d.ah.x: {{x}}
  d.ah.y: {{y}}
{{/d.ah}}
/d.ah:

出力結果。


$ ruby ./hasharray.rb
d: #&lt;D:0x100319d80&gt;
d.h: namenamehogesymbsymbhoge
d.h.symb: symbhoge
d.h.name: namehoge
d.a: item1item2
#d.a:
item1
item2
/d.a:
d.ah: x1xy1yx2xy2y
#d.ah:
#&lt;Sample:0x100319d58&gt;
#&lt;Sample:0x100319d58&gt;
/d.ah:
#d.ah:
  d.ah.x: 1x
  d.ah.y: 1y
  d.ah.x: 2x
  d.ah.y: 2y
/d.ah:

(・w・) (・w・) (・w・)
Ref.
-{{ mustache }}
-mustache(5) -- Logic-less templates.
-どこでも活躍できるテンプレートエンジン「Mustache」 | Mach3.laBlog

tags: ruby mustache zurazure

Posted by NI-Lab. (@nilab)