Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

Ruby on Rails: conditionally display a partial

I'm not sure if I'm doing the best approach here, but I have a block of data that I want to show after a search is done and to not be there at all before. First of all, there is nothing to show, and second the model it references is nil so it throws an exception.

I placed this block in a partial template and added it the appropriate spot in my layout. Is there a way to cleanly render the partial conditionally? Is there a better way to approach this problem?

question from:https://stackoverflow.com/questions/2376482/ruby-on-rails-conditionally-display-a-partial

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...