1
1

More than 3 years have passed since last update.

ヘルパーで部分テンプレート(パーシャル)を返す

Last updated at Posted at 2020-09-29

ヘルパーで部分テンプレート(パーシャル)を返す方法

if文を使って条件ごとに異なるパーシャルを返したい場合があると思います。

しかし"html.erb"ファイルの中でif文を書くとどうしてもコードが長くなってしまいますよね。
例えばこんな風に、、、

sample.html.erb
<% if A == A %>
 <%= render 'follow_button' %>
<% else %>
 <%= render 'unfollow_button' %>
<% end %>

こんな時はヘルパーメソッドに処理をまとめるとスッキリします。⬇︎

users_helper.rb
module UsersHelper

  def follow_unfollow_button(user)
    if A == A 
     render 'follow_button' 
    else 
     render 'unfollow_button' 
    end 
  end

end

ビューでhelperメソッドを使うと、、

sample.html.erb
<%= follow_unfollow_button(@user) %>

1行でスッキリしました。

まとめ

slimやhamlを使用していればif文も多少は短くなるのですが、いずれにせよビューの中にロジックが書かれているとやはりコードの可読性が下がってしまいます。
できるだけif文などのロジックやhelperやdecoratorにまとめた方が良いと思いました。

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