Rails 渲染中的 :locals 是什么?
这是渲染的 API 定义:
render(options = {}, locals = {}, &block)
Returns the result of a render that’s dictated by the options hash. The primary options are:
:partial - See ActionView::Partials.
:file - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
:inline - Renders an inline template similar to how it’s done in the controller.
:text - Renders the text passed in out.
这里没有解释 locals 的目的是什么?当地人有什么用?
Here is the API definition for render:
render(options = {}, locals = {}, &block)
Returns the result of a render that’s dictated by the options hash. The primary options are:
:partial - See ActionView::Partials.
:file - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
:inline - Renders an inline template similar to how it’s done in the controller.
:text - Renders the text passed in out.
There is no explanation about what's the purpose of locals here? What's locals for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将局部变量传递给部分模板,而不是控制器实例变量。
请参阅布局和渲染指南中的第 3.4.4 节“传递局部变量”。
To pass local variables to the partial template, as opposed to controller instance variables.
See Section 3.4.4, Passing Local Variables in the Layouts and Rendering Guide.
例如:
<%= render :partial => “帐户”%>
这意味着该部分已经有一个名为
@account
的实例变量,并且您将其传递给该部分。<%= 渲染:部分 => “帐户”,:locals => {:帐户=> @buyer } %>
这意味着您将一个名为
@buyer
的本地实例变量传递给account
部分,并且account
部分中的变量称为@帐户
。即,哈希{ :account =>; @buyer }
for:locals
仅用于将局部变量传递给局部变量。您还可以以相同的方式使用关键字as
:<%= 渲染:部分 => “合同”,:as => :协议
这与:
相同
<%= 渲染:部分 => "合同", :locals => {:协议=> @contract }
For example:
<%= render :partial => "account" %>
This means there is already an instance variable called
@account
for the partial and you pass it to the partial.<%= render :partial => "account", :locals => { :account => @buyer } %>
This means you pass a local instance variable called
@buyer
to theaccount
partial and the variable in theaccount
partial is called@account
. I.e., the hash{ :account => @buyer }
for:locals
is just used for passing the local variable to the partial. You can also use the keywordas
in the same way:<%= render :partial => "contract", :as => :agreement
which is the same as:
<%= render :partial => "contract", :locals => { :agreement => @contract }