Haml / Sass / CoffeeScriptでビューを書く ~Haml~

Hamlが5分で分るチートシート | 酒と涙とRubyとRailsと

RailsのHTMLテンプレートエンジン Haml入門 - Rails Webook

Convert HTML/ERB to HAML online

 

手始めにHamlから

GemfileにHamlを追加

# Haml
gem 'haml-rails'

 

基本記法

<strong> Hello!</strong>

              ↓Haml

%p Hello!

で済む

 

階層構造

<gee>

  <whiz>

    Wow this is cool!

  </whiz>

</gee>

              ↓Haml↓             

%gee

  %whiz

    Wow this is cool!

 

属性情報の付加

<div id="my-id">

  Contents

<div>

<div class="my-class">

  Contents

<div>

              ↓Haml

%div{id: "my-id"} Contents

%div{class: "my-class"} Contents

               or

#my-id Contents

.my-class Contents

 

HTMLに記述されないコメント

-# test comment

 

HTMLに残すコメント

<!-- This is the pean... -->

              ↓Haml

/ This is the pean...

 

Rubyの変数を使う

<div class="fuga">

  test message is fuga

  like

</div>

              ↓Haml

- hoge = "fuga"

- hagu = 'like'

%div{class: hoge}

  test message is #{hoge}

  = hagu

 

Rubyのif文やcase文を埋め込む

<p> 2? </p>

              ↓Haml

%p

 - case 2

 - when 1

   = "1!"

 - when 2

  = "2?"

 

Rubyのブロックを使う

<p>42</p>

<p>43</p>

<p>44</p>

<p>45</p>

<p>46</p>

<p>See, I can count!</p>

              ↓Haml

- (42...47).each do |i|

  %p = i

%p See, I can count!

 

HTMLのエスケープ

&= "I like cheese & crackers"

とかくと

I like cheese &amp; crackers とエスケープされる

 

フィルタ機能

ネスト以降を全て特定の言語としてコンパイルできる例:Markdown

 

<p>

 <h1>Greetings</h1>

 <p>Hello, <em>Word</em></p>

</p>

              ↓Haml

:markdown

  # Greetings

  Hello, *World*

<他の例>

01) :coffee => CoffeeScript
02) :css => CSS
03) :erb => RHTML template(eRubyを実行できる)
04) :escaped => HTMLエスケープされたテキスト
05) :javascript => JavaScript
06) :less => LESS
07) :markdown => マークダウン
08) :plain => プレーンなテキスト
09) :ruby => Rubyのコード
10) :sass => SASS
11) :scss => SCSS

 

DOCTYPEの宣言

<!DOCTYPE html>

              ↓Haml

!!! 5

 

エスケープ、非エスケープ

&= エスケープした文字列を出力したい

!= エスケープせずに出力したい

 

一行が長くなる場合の改行

= link_to_remote 'Add to cart',
url: { action: 'add', id: product.id },
update: { success: 'cart', failure: 'error' }

 

data属性はHashのネストで表現

%span{ data: { hogehoge: 'mokemoke' } }