2
2

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 5 years have passed since last update.

【Rails】Slim基本文法【初心者】

Posted at

はじめに

Railsを使った開発で使うことになるであろうSlimについて簡潔にまとめてみました。

Slimとは

Railsで使用できるRuby製のHTMLテンプレートエンジン。

Slimのメリット

HTMLをよりシンプルに見やすく書くことができる。

Slim導入

Slimジェネレータを提供してくれるslim-railsとERB形式のファイルをSlim形式に変換してくれるhtml2slimという2つのGemをインストール

gem 'slim-rails'
gem 'html2slim'

Slimへ変換

すでにあるerb形式のファイルをSlim形式に変換するときは以下のコマンド

$ bundle exec erb2slim 変換したいerbファイルのパス --delete

Slim基本文法

<>が不要、や<% end %>等の閉じタグも不要
<%= %>=
<% %>-
id指定 → #
class指定 → .
コメント → /
改行 → |

ERBとSlimの比較

最初にERB形式

example.html
<div class="contents nav">
  <ul class="navbar-nvv">
    <% if current_user %>
      <li><%= link_to("MyPage", user_path, class: "nav-link") %></li>
    <% else %>
      <li><%= link_to("LogIn", login_path, class: "nav-link") %></li>
    <% end %>
  </ul>
  # これはコメントです
  <p id="greeting">Hello World!!</p>
</div>

次がSlim形式

example.html.slim
.contents.nav
  ul.navbar-nav
    - if current_user
      li= link_to "MyPage", user_path, class: "nav-link"
    - else 
      li= link_to "LogIn", login_path, class: "nav-link"
  / これはコメントです
  p#greeting Hello World!!

さいごに

かなりスッキリしましたね!
以上Slimの基本文法でした。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?