1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Haml】よく使う書き方まとめ

Posted at

個人的に、業務で使うhamlの書き方をまとめました。

head部分

index.html.haml
= content_for :meta_head do
  %title hoge
  %meta{:content => "hoge", :name => "description"}/
  %meta{:content => "hoge", :property => "og:title"}/
  %meta{:content => "article", :property => "og:type"}/
  %meta{:content => "hoge", :property => "og:description"}/
  %meta{:content => request.url, :property => "og:url"}/
  %meta{:content => "Foo", :property => "og:site_name"}/
  %meta{:content => "Bar"}", :property => "og:image"}/
  = stylesheet_link_tag "hoge.css", media: "all"
  = javascript_include_tag "hoge"

body部分

index.html.haml
#content
  .content-head-img
    .top-image-pc
      =image_tag("pc.png")
    .top-image-sp
      =image_tag("sp.png")
    .content-head-inner
      .inner-txt
        hogehoge
      .inner-arrow
        = image_tag @event.eye_catch.to_s, size: "10x10", alt: "hoge"
      =link_to "hoge","/content/index", :class => "btn"

# = id属性 . = class属性
=image_tag 第1引数は画像ファイルへのパスを指定 / 第2引数は表示したいサイズを指定 / 第3引数はalt属性の指定
link_to 第1引数はテキスト / 第2引数はURLリンク先

同じdivでも、class付与しただけのdivと複数の属性を持っているdivでは書き分けたりしていますが、この辺りは会社のコーディングルールに従うべきですね。

index.html.haml
.hogehoge
%div{class:"hogehoge",:role=>"dialog", "aria-hidden"=>"false", :id=>"hogeeee"}

if文とループ文の組み合わせ

bootstrapも途中で入っています。

index.html.haml
- if @hoge.present?
  - @hoge.each do |hoge|
    - if @foo != hoge.id
      - @foo = hoge.id
      .hoge-section
        %li.hoge-recommend-item
          .row
            -if hoge.image.present?
              .col-xs-12.col-md-2.col-lg-12.hoge-container
                .hoge-container-content
                  %div
                    = image_tag(hoge.image.thumb)
            -else
              .col-xs-12.col-md-2.col-lg-12.hoge-container
                .top-recommend-profile-box
                  %div
                    = image_tag('default_story.jpg')

基本的に、view部分にロジックは書かずcontrollerに書くことで可読性を上げていることを重視しています。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?