LoginSignup
62
59

【Rails】haml の書き方

Last updated at Posted at 2017-05-01

hamlについて

haml だと html が簡潔に書けます。
haml ファイルが html に変換されます。

hamlの記法

haml と erb の対応を書きます。
上が erb 、下が haml です。

ネスト

haml では、<>>で囲まれている状態をインデントで表します。

erb
<div class="wrapper">
  <div class="inner">
    <p>
      インナーです。
    </P>
  </div>
</div>
haml
.wrapper
  .inner
    %p
      インナーです。

<%= %>

erb
<%= @user.name %>
haml
= @user.name

<% %>

erb
<% if @user.present? %>
haml
- if user.present?

タグ

erb
<p>ユーザー一覧</p>
haml
%p
  ユーザー一覧

クラス

erb
<div class="title">タイトル</div>
haml
.title
  タイトル

ID

erb
<div id="user_id">ユーザーのID</div>
haml
#user_id
  ユーザーのID

属性

erb
<div class="maintenance" style="color:lightgray">メンテナンス中</div>
haml
.maintenance{ style: "color:lightgray" }
  メンテナンス中

コメントアウト

erb
<!-- ユーザー一覧 -->
haml
1)html に変換される
/ ユーザー一覧
2)html に変換されない
-# ユーザー一覧

フィルター

フィルターとは、hamlファイル内で、haml以外のプログラミング言語を書けるようにする標識のことです。
先頭にコロン「:」が付いています。
http://haml.info/docs/yardoc/file.REFERENCE.html の Filters の所に一覧がのっています。


cssを入れる

haml
:css
  .title {
    color: gray;
  }

javascriptを入れる

haml
:javascript
  $(window).ready(function() {
    $('.title').css('color', 'green');
  });

  // ruby を埋め込む時は'#{ rubyコード }'
  root_url = '#{root_url}'
62
59
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
62
59