Jas*_*ost 8 yield content-for ruby-on-rails-3
我在我的应用程序中有大块的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>
Run Code Online (Sandbox Code Playgroud)
我使用以下代码设置块的内容
<%= 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" %>
Run Code Online (Sandbox Code Playgroud)
问题是如果我在同一布局上多次使用它,原始块中的内容将附加到辅助块
我已经尝试创建一个自定义帮助方法来解决它,但它不会返回任何内容
def overwrite_content_for(name, content = nil, &block)
@_content_for[name] = ""
content_for(name, content &block)
end
Run Code Online (Sandbox Code Playgroud)
我可能也会对此完全错误,如果有更好的方法可以让内容像我一样工作,我想知道.谢谢.
dan*_*lee 15
在Rails 4中,您可以传递:flush参数来覆盖内容.
<%= content_for :block_head, 'hello world', :flush => true %>
Run Code Online (Sandbox Code Playgroud)
或者,如果你想通过一个街区,
<%= content_for :block_head, :flush => true do %>
hello world
<% end %>
Run Code Online (Sandbox Code Playgroud)
比照 这个帮助器的源代码了解更多细节
您应该将 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
Run Code Online (Sandbox Code Playgroud)
请注意,如果您的块产量为零,则旧内容将被保留。然而,整个想法听起来不太好,因为你显然做了两次渲染(或至少对象实例化)。
| 归档时间: |
|
| 查看次数: |
4987 次 |
| 最近记录: |