LoginSignup
12
10

More than 5 years have passed since last update.

hamlでタグを改行しない方法の整理

Last updated at Posted at 2017-02-21

はじめに

この記事は、hamlでの改行を制御する方法をまとめたものです。
hamlから作られるhtmlタグは、基本的に改行が入り見やすいものになっています。
しかし場合によっては改行を消したいときもあるでしょう。
デザインにも影響します。
今回は、hamlでタグを改行しない方法を整理して解説します。

基本形

haml

%ul
  %li
    %span
  %li
    %a

html

<ul>
  <li>
    <span></span>
  </li>
  <li>
    <a></a>
  </li>
</ul>

内側の改行を消す

haml

1番目のliの直後に<を書いてみます。

%ul
  %li<
    %span
  %li
    %a

html

すると、liの内側の改行が削除されるため、li, spanがワンラインで書かれます。

<ul>
  <li><span></span></li>
  <li>
    <a></a>
  </li>
</ul>

外側の改行を消す

haml

liの直後に>を書いてみます。

%ul
  %li>
    %span
  %li
    %a

html

すると、liの外側の改行が削除されるため、ulと次のliが改行なしで表示されます。

<ul><li>
    <span></span>
  </li><li>
    <a></a>
  </li>
</ul>

>親のタグとの改行を消すという説明がされている場合がありますが、正しくはこうなります。

親と子の改行を抑止する場合は以下のようにするのが良さそうです。

%ul<
  %li
    %span
  %li
    %a
<ul><li>
  <span></span>
</li>
<li>
  <a></a>
</li></ul>

まとめ

hamlの改行の削除に関しては、<は内側、>は外側と覚えておくのが良さそうです。

確認に使ったサイト

追記

公式ドキュメントにキャッチーな説明が書かれていました:bow:
http://haml.info/docs/yardoc/file.REFERENCE.html#whitespace_removal__and_

You can think of them as alligators eating the whitespace: > faces out of the tag and eats the whitespace on the outside, and < faces into the tag and eats the whitespace on the inside.

アリゲーター🐊

12
10
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
12
10