Render @object and locals vs render :partial

女生的网名这么多〃 提交于 2019-12-01 00:30:35

问题


I want to pass a local variable that contains the origin to come on a specific page, this variable contains just a symbol with the value.

When I use this code it works perfect, the origin variable is accessible in the partial :

render :partial => "products", :collection => @products, :locals => {:origin => :gallery}

But when I use this code, the origin is not set and not accessible in the partial :

render @products, :locals => {:origin => :gallery}

What is the difference here? Is the second line of code not render the partial like the first line?


回答1:


<%= render @products %>

Is indeed the shorthand syntax for rendering a partial. But with the shorthand syntax, Rails will ignore the ":locals" variable. There's more on this in the Rails Guides.

So if you want to pass extra options to the render, you have to specify ":partial => ...". If you want to know why this happens, you can take a look at the Rails source.




回答2:


There's a good explanation here: Rails: confused about syntax for passing locals to partials

The short version is that you can just omit :locals in the second example:

render @products, :origin => :gallery


来源:https://stackoverflow.com/questions/9990539/render-object-and-locals-vs-render-partial

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