1
1

More than 3 years have passed since last update.

hamlの書き方 基礎編

Posted at

普段htmlを書いていてhamlに慣れていなかったので簡単にhamlの書き方をまとめます。

Hamlファイルの構造

<div id='content'>
  <div class='title'>
    <h1>Teen Wolf</h1>
    <a href='/'>Home</a>
  </div>
</div>

上記はhamlに直すと以下のようになる

#content
 .title
   %h1= @title
   = link_to 'Home', home_url

%

<開始タグ>と<終了タグ>を書く代わりに%をつけるだけで良い

入れ子構造にするときインデントが必須

holidayではタブ一つ分(半角スペース2つ分開けています)

タグの中身

#content
 .title
   %h1= @title
   = link_to 'Home', home_url

id

divは省略可能なので%divも取り払って#contentとなる

class

同様に%divを取り払ってclassは.titleになる

erbファイルをhamlに変換する

- if @x.present?
        %item
          .item
            %h2 商品詳細
          .item_detail
            - @item_units.each do |i|
              %dl.p-item__list
                - if %i.quantity != nil && %i.price != nil
                  %dt.p-item__list-term
                    = "#{i.quantity}#{i.quantity_description}"
                  %dd.p-item__list-description
                    = "#{number_with_delimiter(i.price)}円(税込)"

-

eachやifなどロジックの始まりに-記号をつける

=

=で評価されたruby式は文として挿入される

#{}

hamlの中でrubyの式を展開する場合に用いる

参照

haml公式

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1