Ruby-on-rails 将变量传递给部分,rails 3?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4700617/
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-03 00:06:33  来源:igfitidea点击:

Pass a variable into a partial, rails 3?

ruby-on-railsrubyruby-on-rails-3

提问by Elliot

I have a loop like such:

我有一个这样的循环:

<% @posts.each do |post| %>
  <% render middle %>
<% end %>

Then in my middle partial, how do I access the current post?

然后在我的中间部分,我如何访问当前帖子?

回答by polarblau

Try this:

尝试这个:

<% @posts.each do |post| %>
  <%= render 'middle', :post => post %>
<% end %>

Like this you'll have a local variable postavailable within the partial.

像这样,您将post在部分中拥有一个可用的局部变量。

回答by Stefaan Colman

Give it to the partial as a local variable

将其作为局部变量提供给部分

<%= render :partial => 'middle', :locals => { :post => post } %>

Of course, rails also has a shortcut for rendering collections:

当然,rails 也有渲染集合的捷径:

<%= render :partial => 'post', :collection => @posts %>

In this case it will call the partial post for every post with a local variable 'post'

在这种情况下,它将使用局部变量“post”为每个帖子调用部分帖子

You can even render a spacer template between each post:

您甚至可以在每个帖子之间渲染一个间隔模板:

<%= render :partial => 'post', :collection => @posts, :spacer_template => 'post_divider' %>

回答by Felix Andersen

<% @posts.each do |post| %>
  <% render middle, :post => post %>
<% end %>

You can now access post as the local variable postin the partial

您现在可以访问 post 作为局部变量post中的局部变量

回答by sevenseacat

Replace <%= render middle %>with <%= render middle, :post => post %>. Then in your middlepartial, you can access the postvariable.

替换<%= render middle %><%= render middle, :post => post %>。然后在您的middle部分中,您可以访问该post变量。