我正在研究content_for 的工作原理并观察了block.call
方法中的内容capture_erb_with_buffer
。它显然神奇地写入缓冲区变量,然后将其修剪。但是,我认为这已被弃用,您现在就可以打电话<%=yield :tag%>
了。这是如何运作的?如果我从 ERB 模板调用 yield 到哪里?
一个简单的代码示例来说明这一点将不胜感激。
我正在研究content_for 的工作原理并观察了block.call
方法中的内容capture_erb_with_buffer
。它显然神奇地写入缓冲区变量,然后将其修剪。但是,我认为这已被弃用,您现在就可以打电话<%=yield :tag%>
了。这是如何运作的?如果我从 ERB 模板调用 yield 到哪里?
一个简单的代码示例来说明这一点将不胜感激。
我不确定yield
ERB 级别的功能如何,但我知道它在应用于布局时是如何工作的。
这是一个示例 layout.html.erb 文件:
<html>
<head>
<title> <%= @title || 'Plain Title' %> </title>
<%= yield :head %>
</head>
<body>
<div id='menu'>
<%= yield :menu %>
</div>
<div id='content'>
<%= yield %>
</div>
<div id='footer'>
<%= yield :footer %>
</div>
</body>
我已经定义了 4 个 yield(:head、:menu、:footer 和 default) 和一个实例变量 @title。
现在控制器动作可以渲染插入这些位置的视图。请注意,视图在布局之前呈现,因此我可以在视图中定义像 @title 这样的变量,并在布局中定义它。
示例视图:关于页面
<% @title = 'About' %>
<% content_for :menu do %>
<%= link_to 'Back to Home', :action => :home %>
<% end %>
We rock!
<% content_for :footer do %>
An Illinois based company.
<% end %>
编辑页面
<% @title = 'Edit' %>
<% content_for :head do %>
<style type='text/css'> .edit_form div {display:inline-block;} </style>
<% end %>
<% form_for :thing, :html => {:class => 'edit_form'} do |f| %>
...
<% end %>
您可以混合和匹配您想要放入数据的产量,以及将在布局文件content_for :something
中的匹配中插入的内容。yield :something
它甚至适用于局部,局部可以插入自己的 content_for :something 块,该块将与任何其他 content_for 调用一起添加。
execute
这个被调用的小方法ActionView::Base
解释了这一切。
http://google.com/codesearch/p?hl=en#m8Vht-lU3vE/vendor/rails/actionpack/lib/action_view/base.rb&q=capture_helper.rb&d=5&l=337
def execute(template)
send(template.method, template.locals) do |*names|
instance_variable_get "@content_for_#{names.first || 'layout'}"
end
end
该do |*names|... end
块是接收yield
. 您会注意到与过程@content_for_#{names.first}
中设置的变量相匹配content_for
。
它是从#render 中的 AV::TemplateHandlers::Compilable 调用的,我也会假设其他地方。
def render(template)
@view.send :execute, template
end
简单地:
在方法中调用 yield 会执行通过块传递给方法的代码。
例如
def my_method
yield
end
my_method { puts "Hello" }
my_method { puts "World" }
这 5 行将在屏幕上产生以下输出
Hello
World
有关 Ruby中产量的精彩讨论,请参阅以下页面:Ruby Yield