Pass a variable into a partial, rails 3?

匿名 (未验证) 提交于 2019-12-03 02:11:02

问题:

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?

回答1:

Try this:

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

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



回答2:

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:

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

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

You can even render a spacer template between each post:

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


回答3:

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

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



回答4:

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



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