Haml リファレンス
Attributes: {}
Brackets represent a Ruby hash that is used for specifying the attributes of an element.
%html{:xmlns => "http://www.w3.org/1999/xhtml", "xml:lang" => "en", :lang => "en"}is compiled to:
HTML-style Attributes: ()
Haml also supports a terser, less Ruby-specific attribute syntax based on HTML’s attributes.
%html(xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en")%a(title=@title href=href) StuffThis is the same as:
%a{:title => @title, :href => href} Stuff%a(title=@title){:href => href} Stuff
そのうちチートシート作ろう。
注意事項
Ruby ではシンボルにハイフンを含めることが出来ません。ので Haml でハッシュのキーにシンボルを使うときにもハイフンは厳禁です。
例えば Twitter Bootstrap で Modal を使うときに、
<!-- Button trigger modal --> <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>
とありますが、ハッシュキーとして data-toggle や data-target をそのまま使ってはいけません。使うと syntax error, unexpected tLABEL
エラーになってしまいます。ですのでハイフン付きのキーは
%button.btn.btn-primary.btn-lg{type: "button", :'data-toggle' => "modal", :'data-target' => "#myModal"} Launch demo modal
とする((Ruby 2.2以降ならば :'data-toggle' => "modal"
を 'data-toggle': "modal"
と書けます。))か、またはハッシュでは無く丸括弧の引数にして
%button.btn.btn-primary.btn-lg(type="button" data-toggle="modal" data-target="#myModal") Launch demo modal
にしましょう。
ラクなのはハッシュと丸括弧を混ぜた表記だと思います。ありがたいことに、ハッシュと丸括弧の順序は問いません。
%button.btn.btn-primary.btn-lg{type: "button"}(data-toggle="modal" data-target="#myModal") Launch demo modal %button.btn.btn-primary.btn-lg(data-toggle="modal" data-target="#myModal"){type: "button"} Launch demo modal
また、ハッシュの中にハッシュを入れるとシンボル名をハイフンで繋いだキーを生成してくれるという設定を利用して次のようにも書けます(読みやすいような読みづらいような)。
%button.btn.btn-primary.btn-lg{type: "button", data: {toggle: "modal", target: "#myModal"} } Launch demo modal