Ruby on Rails: conditionally display a partial

拥有回忆 提交于 2019-12-03 09:21:15

Ruby allows you to do nice things like this:

<%= render :partial => "foo/bar" if @conditions %>

To make this a bit easier to read and understand, it can be written as:

<%= render(:partial => "foo/bar") if @conditions %>

render is a function, and you pass it a hash that tells it which partial to render. Ruby allows you to put things on one line (which often makes them more readable and concise, especially in views), so the if @conditions section is just a regular if statement. It can also be done like:

<% if @conditions %>
  <%= render :partial => "foo/bar" %>
<% end %>

Edit:

Ruby also allows you to use the unless keyword in place of if. This makes code even more readable, and stops you from having to do negative comparisons.

<%= render :partial => "foo/bar" if !@conditions %>
#becomes
<%= render :partial => "foo/bar" unless @conditions %>

One easy way is to use a helper method. Helpers tend to be a bit cleaner than putting logic directly in the view.

So, your view might be something like :

<%= render_stuff_conditionally %>

and your helper would have a method to control this:

def render_stuff_conditionally
  if @contional_check
    render :partial => 'stuff'
  end
end

where obviously things are named more appropriately

Assuming I am following you right, you do this at the view level.

<% if !@my_search_data.nil? %>
<% render :partial => 'foo/bar' %>
<% end %>

Hope that helps. If not, maybe post an example of your code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!