我的应用程序中有大块HTML,我想将其移动到共享模板中,然后使用content_for与yield一起插入必要的内容。然而,如果我在同一个布局文件中使用它不止一次,content_for只是附加到之前的使这个想法不太好。有解决办法吗?
<div class="block side">
<div class="block_head">
<div class="bheadl"></div>
<div class="bheadr"></div>
<h2><%= yield :block_head %></h2>
</div>
<div class="block_content">
<%= yield :block_content %>
</div>
<div class="bendl"></div>
<div class="bendr"></div>
</div>
和我使用下面的代码设置块
的内容 <%= overwrite_content_for :block_head do -%>
My Block
<% end -%>
<%= overwrite_content_for :block_content do -%>
<p>My Block Content</p>
<% end -%>
<%= render :file => "shared/_blockside" %>
问题是,如果我在同一布局中多次使用这个,原始块的内容就会附加到第二个块
我已经尝试创建一个自定义助手方法来绕过它,但是它不返回任何内容
def overwrite_content_for(name, content = nil, &block)
@_content_for[name] = ""
content_for(name, content &block)
end
我也可能是去这个完全错误的,如果有任何更好的方法让内容像这样工作,我想知道。谢谢。
在Rails 4中,您可以通过:flush参数来覆盖内容。
<%= content_for :block_head, 'hello world', :flush => true %>
或者,如果你想传递一个块,
<%= content_for :block_head, :flush => true do %>
hello world
<% end %>
cf。
你应该定义你的overwrite_content_for如下(如果我理解正确的话):
def overwrite_content_for(name, content = nil, &block)
content = capture(&block) if block_given?
@_content_for[name] = content if content
@_content_for[name] unless content
end
注意,如果你的块产生nil,那么旧的内容将被保留。然而,整个想法听起来并不好,因为您显然要做两次渲染(或至少对象实例化)。
你总是可以直接传递内容而不依赖于块:
<% content_for :replaced_not_appended %>
我不确定我是否真的理解你的问题-这里是一个方法在代码工作:
视图:
<% content_for :one do %>
Test one
<% end %>
<% content_for :two do %>
Test two
<% end %>
<p>Hi</p>
application.html.erb
<%= yield :one %>
<%= yield %>
<%= yield :two %>
Railsguides: http://guides.rubyonrails.org/layouts_and_rendering.html using-content_for
您可以这样使用命名的content_for
和yield
块:
视图:
<% content_for :heading do %>
<h1>Title of post</h1>
<% end %>
<p>Body text</p>
<% content_for :footer do %>
<cite>By Author Name</cite>
<% end %>
在布局中:
<%= yield :heading %>
<%= yield %>
<%= yield :footer %>
你当然可以按任何顺序定义它们。
文档:http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html