Ruby on Rails:有条件地显示部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2376482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:20:54  来源:igfitidea点击:

Ruby on Rails: conditionally display a partial

ruby-on-railsrubypartial-views

提问by Donald Hughes

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?

我将此块放在部分模板中,并将其添加到布局中的适当位置。有没有办法干净地有条件地渲染部分?有没有更好的方法来解决这个问题?

回答by Mike Trpcic

Ruby allows you to do nice things like this:

Ruby 允许你做这样的好事:

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

renderis 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 @conditionssection is just a regular if statement. It can also be done like:

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

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

Edit:

编辑:

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

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

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

回答by Pete

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

显然,事物的命名更恰当

回答by bojo

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.

希望有帮助。如果没有,也许可以发布您的代码示例。