1
1

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.

[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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?