Skip to content

Instantly share code, notes, and snippets.

@seki
Forked from makoto/gist:1159123
Created September 5, 2011 13:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seki/1194969 to your computer and use it in GitHub Desktop.
Save seki/1194969 to your computer and use it in GitHub Desktop.
drubyコラム: Mustache (定型文書の生成とERB)

「{」の見た目から名付けられたMustacheというライブラリーが人気です。

https://github.com/defunkt/mustache

このテンプレートの面白いところは「極力ロジックを書かない」ことに注力したテンプレートだということです。以下がMustacheのホームページから抜粋した例です。

Hello {{name}}
You have just won {{value}} dollars!
{{#in_ca}}
Well, {{taxed_value}} dollars, after taxes.
{{/in_ca}}

分岐とイタレーションがある程度なのですが、では複雑なロジックはどう表現するかというと、今回のERBの例と同じようにViewクラスとして別に定義しています。

class Simple < Mustache
  def name
    "Chris"
  end

  def value
    10_000
  end

  def taxed_value
    value * 0.6
  end

  def in_ca
    true
  end
end

Mustacheの強みはロジックがあまりないため構文がシンプルで移植が簡単なため、javascriptやpythonといった様々な言語用に移植されていますが、Viewクラスに関する考えとかなり共通点が多いのではないでしょうか。

Mustacheを使ったスクリプトは一見Rubyの文字列リテラルの置換によく似ていますね。{{}}はRubyの文字列リテラルにおける #{...} を使った置換と同じです。 {{#...}} {{/...}}などの制御構造が導入されているのがRubyの文字列リテラルとの違いです。 ERBを書いておいてなんなんですが、Rubyの文字列リテラルに簡単な制御構造が導入されたら、いろいろなテンプレートを覚えたり、発明したりしなくてすむのになあ、とよく思います。 もっとも、簡単な制御構造は素のRubyで書いた方がわかりやすいかもしれませんが。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment