有条件地显示部分

有条件地显示部分

本文介绍了Ruby on Rails:有条件地显示部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我在这里是否采用了最佳方法,但我有一个数据块,我想在搜索完成后显示,而在此之前根本不在那里.首先,没有什么可显示的,其次它引用的模型是 nil,所以它会抛出异常.

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?

推荐答案

Ruby 允许你做这样的好事:

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 是一个函数,你传递给它一个哈希值,告诉它要渲染哪个部分.Ruby 允许您将内容放在一行(这通常使它们更具可读性和简洁性,尤其是在视图中),因此 if @conditions 部分只是一个常规的 if 语句.也可以这样做:

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

Ruby 还允许您使用 unless 关键字代替 if.这使代码更具可读性,并使您不必进行负面比较.

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

这篇关于Ruby on Rails:有条件地显示部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 23:25