27
21

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.

【初心者向け】slimの書き方

27
Last updated at Posted at 2019-06-24

はじめに

職場で初めてslim記法に触れて全く読めなかったので、基礎だけでも押さえようと記事にまとめてみました。
修正点等ありましたら教えていただけると助かります。

参考

RailsのHTMLテンプレートエンジン、Slimの基本的な記法
【爆速で習得】Railsでslimを使う方法から基本文法まで

slimとは

1:Ruby製のテンプレートエンジン
2:高速、軽量
3:htmlの閉じタグ不要
4:条件分岐などのend不要
5:インデントによって階層構造を表現するため、 ずれるとエラーになる

概要

大まかな概要はこちら。

<>不要
<%= %> → =
<% %> → -
コメント → /
id指定 → #
class指定 → .

書き方一覧

a

example.html
<a href="www.example.com">ホームページ</a>
example.slim
a href="www.example.com" ホームページ

p

example.html
<p>
      ほげほげ ふがふが
      ほげほげ ふがふが
</p>
example.slim
/ (改行する場合はパイプ(|)を使う)
p
  |
    ほげほげ ふがふが
    ほげほげ ふがふが

/ パイプの後ろに書いても良い
p
  | ほげほげ ふがふが

erb記法

<%> <%> → -

example.slim
- if logged_in?
 li = link_to '投稿する', new_path
 li = link_to 'ログアウト', logout_path
- else
 li = link_to 'ログインする', '/auth/twitter'

<%=> <%> → =

example.slim
= form_for @micropost, :html => { class: "foo"} do |f|
  = f.text_field :title, placeholder: "内容"
  = f.submit "投稿する", class: "btn"

コメントアウト /

example.slim

 / li = link_to 'ログアウト', logout_path

クラス . ID #

example.slim

<div class="text">
</div>

<div id="text">
</div>

/ 正 (divタグ省略)
.text
# text

/ 複数クラスの記載は.で繋ぐ
.text.text-plain

render yield

new.html.slim
/ 誤
= render 'form', user: @user

/ 正 (render yield は ==)
== render 'form', user: @user

if

example.html
<% if current_user.nil? %>
  <li>新規登録</li>
<% else %>
  <li>ログイン</li>
<% end %>
example.slim
- if current_user.nil?
  li 新規登録
- else
  li ログイン

/ end不要
27
21
1

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
27
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?