LoginSignup
26
19

More than 5 years have passed since last update.

slimで制御文を扱うには(rails)

Last updated at Posted at 2015-12-24

最近、社内ではerbをslimに書き換えたほうがバグも減るし、楽!ということでちょっとずつ書き換わっているのですが、ここで思わぬところで詰まったのでメモしておきます。

はじめに

まず基本をおさらいしておきます。

<!DOCTYPE html>
<html>
<head>
  <title>SlimTest</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body>

<header id="header">
  <h1 class="title logo">Slim Test</h1>
</header>

<%= yield %>

<% if @user.present? %>
  <%= link_to @user.name + 'を見てみる', profile_path(user_id: @user.id),{class:'hogemoge'} %>
<% end %>

</body>
</html>

ってのは

doctype html
html
  head
    title SlimTest
    = stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true
    = javascript_include_tag 'application', 'data-turbolinks-track' => true
    = csrf_meta_tags

  body

    header#header
      h1.title.logo Slim Test

    == yield

    - if @user.present?
      = link_to @user.name + 'を見てみる', profile_path(user_id: @user.id),{class:'hogemoge'}

と記述することができます。ここまではなんとなーくかけると思います。
ここで、一瞬?となる可能性が高いlink_toの書き方も一緒にのっけました!

制御文を使うには

ここで変数を扱ってみます。

  - if action_name == 'hoge'
    span.abcd
      = profile(@user)

  .btn_list  class="#{'dnone' if action_name == 'hogemoge'}"
    - if action_name == 'edit'
      = render_list_btn(user, "profile").html_safe
    - else
      = render partial: '/user/profile_for_list', locals: { user: user }

となります。さて、これのどこでつまったのかというと

class="#{'dnone' if action_name == 'hogemoge'}"

ここの部分!
erbで記述すると

class=<%= "dnone" if action_name == 'hogemoge' %>

と、こんな風になると思います。

なので普通に考えると

class="dnone" = if action_name == 'hogemoge'

とかでいけるのかなーと思いましたがエラー。
先ほどのような書き方で無事解決することができました。

26
19
2

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
26
19