0
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の書き方

Last updated at Posted at 2022-04-19

はじめに

仕事でhtmlではなくhamlを使うと言うので急いでドットインストールで学習しました。備忘録として残します。

基本的な書き方

hamlを使う場合、基本的には頭に%をつけます。そうすることで下記のようにhtmlへ変換されます。

test.haml
!!!
%html
  %body
    hello world!
test.html
<!DOCTYPE html>
<html> 
  <body>
    hello world!
  </body>
</html>

とても便利!

属性の書き方

属性を書く場合は2パターンあります。{}を使う場合と()を使う場合です。

test.haml
!!!
%html{:lang => "ja"}
  %head
    %meta(charset="UTF=8")
test.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF=8">
  </head>
</html>

{}の場合はシンボルと=>、()の場合は=を使って表します。

コメントアウト

/ コメント  htmlにも反映される。
-#  コメント htmlに反映されない

改行のコントロール

hamlの見た目を意識して次のように記述するとhtmlにはバランスが悪く表示されてしまします。

test.haml
%div
  %ul
    %li
      test
test.html
<div>
  <ul>
    <li>
      test
    </li>
  </ul>
</div>

そこで<>を使います。li要素の末尾に<を記入すると文字列が

内1行で表示されます。
test.haml
%div
  %ul
    %li<
      test
test.html
<div>
  <ul>
    <li>test</li>
  </ul>
</div>

さらに子要素の末尾に>を記入すると親要素内1行で表示されます。

test.haml
%div
  %ul
    %li<>
      test
test.html
<div>
  <ul><li>test</li></ul>
</div>

属性の記述

属性を記述するには2通りの記法があることは先でも述べました。
{}を使用する場合では {:属性 => 属性値}となります。()を使用する場合は(属性="属性値")となります。

test.haml
%div{:id => "main"}
%div(id="main")

どちらで書いても下のようになります。

test.html
<div id="main">
</div>

また、divはよく使用されるものなので、次のように記入しても同じです。

test.haml
%div{:id => "main", :class => "myClass"}
%div(id="main" class="myClass")
%div#main.myClass
#main.myClass

全て下と同じです。

test.html
<div id="main" class="myClass>
</div>

最後の行はすでに%divまで省略しています。

フィルター

hamlにはフィルターを設けることができます。以下css,script,escapeなど使えます。

test.haml
:css
    .myStyle {
       color: red;
  }

:javascript
  alert(1);
  if (1) {
      alert(2);
  }

%div
    :escaped
      <html>
    </html>

全て下と同じです。

test.html
<style>
  .myStyle {
    color: red;
  }
</style>

<script>
  alert(1);
  if (1) {
    alert(2);
  }
</script>

<div>
    &lt;html&gt;
    &lt;/html&gt;
</div>

以上

参考

ドットインストール
https://dotinstall.com/

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