Rails:对将局部变量传递给局部变量的语法感到困惑 [英] Rails: confused about syntax for passing locals to partials

查看:62
本文介绍了Rails:对将局部变量传递给局部变量的语法感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

了解 Rails 在渲染部分(并将局部变量传递给它们)方面的魔力".

Understanding Rails "magic" with regards to rendering partials (and passing locals into them).

为什么这样做:

<%= render "rabbits/form" %>

这项工作:

<%= render "rabbits/form", :parent => @warren, :flash => flash %>

但这确实不起作用:

<%= render "rabbits/form", :locals => { :parent => @warren, :flash => flash } %>

但这确实是:

<%= render :partial =>"rabbits/form", :locals => { :parent => @warren, :flash => flash } %>

另外,我怎样才能查找这些细微差别,这样我就不需要在 S.O. 上打扰别人?

Also, how can I look up these nuances so I don't need to bother people on S.O.?

推荐答案

简而言之,render 方法会查看您传入的第一个参数.如果您传入一个散列(其中包括 :partial =>;'foo', :locals => {blah blah blah}) 然后它会将您的所有参数作为哈希传递并相应地解析它们.

The short answer is the render method looks at the first argument you pass in. If you pass in a hash (which includes :partial => 'foo', :locals => {blah blah blah}) then it will pass in all of your arguments as a hash and parse them accordingly.

如果你传入一个字符串作为你的第一个参数,它假定第一个参数是你的部分名称,并将其余部分作为你的本地变量.然而,在随后的调用中,它实际上分配了 :locals =>your_locals_argument,在本例中是整个 :locals =>{locals hash},而不仅仅是{locals hash};即你最终得到 :locals =>{:locals =>{locals hash}},而不是 :locals =>{locals hash}.

If you pass in a string as your first argument, it assumes the first argument is your partial name, and will pass the remainder as your locals. However, in that subsequent call, it actually assigns :locals => your_locals_argument, which in this case is the entire :locals => {locals hash}, instead of just {locals hash}; i.e. you end up with :locals => {:locals => {locals hash}}, rather than :locals => {locals hash}.

所以我的建议是始终以相同的方式显式地传递值,这样就不会有问题.为了了解这个,我直接上代码本身(actionpack/lib/base.rb,Rails 2中的render()方法;Rails 3不同).这是一个很好的锻炼.

So my advice is just to always explicitly pass values the same way all the time, and you won't have problems. In order to learn about this, I went directly to the code itself (actionpack/lib/base.rb, render() method in Rails 2; Rails 3 is different). It's a good exercise.

此外,不要担心打扰"SO 上的人.这就是这个网站存在的原因.我什至从中学到了一些东西.

Furthermore, don't worry about "bothering" people on SO. That's why this site exists. I even learned something from this.

这篇关于Rails:对将局部变量传递给局部变量的语法感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆