LoginSignup
1
1

More than 3 years have passed since last update.

[Rails] [メモ] <% %>に=をつける時とつけない時

Last updated at Posted at 2020-10-26

この記事ではmacOS Catalina10.15.6にインストールしたRuby 2.6.5を使っています。
ヘルパーメソッドをビューファイルで記述する時、ふとした瞬間に<% %>の=をつけるかつけないかで間違ってしまうので、忘備録として書きました。

<% %>の場合

  • ビューファイルで出力させたくない時に使います。
  • 例えば、if文などの条件分岐やeach文の繰り返し処理の時などです。
#if文
<% if @name == 'hoge' %>
<% end %>

#each文
<% @books.each do |book| %>
<% end %>

<%= %>の場合

  • ビューファイルで記述した処理を出力させたい時に使います。
<%= book.title %>

<%=form_with model: @user, url: user_registration_path, class: 'registration-main', local: true do |f| %>
<% end %>

<%= f.label :email %>

<%= render 'shared/error_messages' %>

まとめ

ざっとまとめると<%= %>方が圧倒的に多いですね。
要するに、ifなどの条件分岐やeachのような繰り返し処理は=をつけないで、その他の画面に出力する処理はつけても良いということです。

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