# File actionpack/lib/action_view/helpers/capture_helper.rb, line 38defcapture(*args)value=nilbuffer=with_output_buffer{value=yield(*args)}ifstring=buffer.presence||valueandstring.is_a?(String)ERB::Util.html_escapestringendend
moduleStorageHelperdefstored_contentcontent_for(:storage)||"Your storage is empty"endend
这个helper和普通的helper一样工作
<%= stored_content %>
你能使用yield即使在样式中已经有一个存在的yield。举例:
12345678910
<%# This is the layout %><htmlxmlns="http://www.w3.org/1999/xhtml"xml:lang="en"lang="en"><head><title>MyWebsite</title> <%= yield :script %></head><body><%=yield%></body></html>
现在,我们将建立一个包含叫script的content_for方法
123456
<%# This is our view %>Pleaselogin!<% content_for :scriptdo%> <script type="text/javascript">alert('You are not authorized to view this page!')</script><% end %>
之后,在另一个视图中,你可以做这样的事情:
12345
<%= link_to 'Logout', :action =>'logout',:remote=>true%><% content_for :script do %><%=javascript_include_tag:defaults%><% end %>
<% content_for :navigationdo%> <li><%= link_to 'Home', :action =>'index'%></li><% end %><%# Add some other content, or use a different template: %><% content_for :navigationdo%> <li><%= link_to 'Login', :action =>'login'%></li><% end %>