Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Haml

概要

テンプレートシステムHamlについて

詳細

HamlはHTML/XHTMLを生成するためのマークアップ言語。
Pythonのようにインデントで構造を表し、HTMLが冗長になる要因でもある<,>のタグの記述や、閉じタグの記載が不要になり記載量が大幅に減ります。

Hamlのインストール

以下のコマンドでインストールします

gem install haml

サンプルコード

# encoding: UTF-8
require 'haml'

engine = Haml::Engine.new(%{
%body
  #div_class_name
    / comments
    %p= hoges
    /
      comment1
      comment2
      comment3
    hoge
  %p
    = Time.now
  %table{width:"100px",height:"200px"}
    %tr
      %th 言語名
      %th 言語作者
    -for language in languages
      %tr
        %td= language[:name]
        %td= language[:creator]
})

data = {
  hoges:'Hoge, Hige, Hage',
  languages:[
    {name:'Java', creator:'James Gosling'},
    {name:'Ruby', creator:'Matz'},
    {name:'Perl', creator:'Larry Wall'}
  ]
}

puts engine.render(nil, data)

出力

<body>
  <div id='div_class_name'>
    <!-- comments -->
    <p>Hoge, Hige, Hage</p>
    <!--
      comment1
      comment2
      comment3
    -->
    hoge
  </div>
  <p>
    2013-04-08 01:06:34 +0900
  </p>
  <table height='200px' width='100px'>
    <tr>
      <th>言語名</th>
      <th>言語作者</th>
    </tr>
    <tr>
      <td>Java</td>
      <td>James Gosling</td>
    </tr>
    <tr>
      <td>Ruby</td>
      <td>Matz</td>
    </tr>
    <tr>
      <td>Perl</td>
      <td>Larry Wall</td>
    </tr>
  </table>
</body>