Return partial template (partial) with helper

How to return a partial template (partial) with a helper

You may want to use an if statement to return different partials for each condition.

However, if you write an if statement in the "html.erb" file, the code will inevitably become long. For example, like this ...

erb:sample.html.erb


<% if A == A %>
 <%= render 'follow_button' %>
<% else %>
 <%= render 'unfollow_button' %>
<% end %>

In such a case, it will be refreshing to summarize the processing in a helper method. ⬇︎

users_helper.rb


module UsersHelper

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

end

If you use the helper method in the view,

erb:sample.html.erb


<%= follow_unfollow_button(@user) %>

It was refreshing in one line.

Summary

If you use slim or haml, the if statement will be a little shorter, but in any case, if the logic is written in the view, the readability of the code will be reduced. I thought it would be better to put it together in logic such as if statements, helpers and decorators as much as possible.

Recommended Posts

Return partial template (partial) with helper
[Template] MySQL connection with Java
Conditional branch with helper method
Return audio data with api.ai webhook
Cloud Dataflow template created with Scala