同一页面上有多个content_for [英] Multiple content_for on the same page

查看:164
本文介绍了同一页面上有多个content_for的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有很大一部分HTML,我希望将其移到共享模板中,然后将content_for与yields一起使用以插入必要的内容.但是,如果我在同一个布局文件中多次使用它,那么content_for只会追加到先前的内容中,从而使该想法无法很好地发挥作用.有解决办法吗?

I have large block of HTML in my application that I would like to move into a shared template and then use content_for with yields to insert the necessary content. However, if I use it more than once in the same layout file the content_for just appends to the previous making that idea not work so well. Is there a solution to this?

<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>

并且我使用下面的代码来设置块的内容

and I use the following code to set the content for the block

    <%= 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" %>

问题是,如果我在相同的布局上多次使用此内容,则原始块中的内容会附加到辅助块中

The problem is if I use this multiple times on the same layout the content from the original block is appended to the secondary block

我尝试创建一个自定义辅助方法来解决它,但是它不返回任何内容

I have tried creating a custom helper method to get around it, however it does not return any content

  def overwrite_content_for(name, content = nil, &block)
    @_content_for[name] = ""
    content_for(name, content &block)
  end

我也可能完全错了,我想知道是否有更好的方法来使内容像这样工作.谢谢.

I may also be going about this completely wrong and if there are any better methods for getting content to work like this I would like to know. Thanks.

推荐答案

您应将您的overwrite_content_for定义为以下内容(如果我正确理解了您的问题):

You should define your overwrite_content_for as the following (if I understand your question correctly):

  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,那么旧内容将被保留.但是,整个想法听起来并不好,因为您显然要进行两次渲染(或至少是对象实例化).

Note, that in case your block yields nil, then the old content will be retained. However, the whole idea doesn't sound good, as you're obviously doing some rendering (or at least object instantiation) twice.

这篇关于同一页面上有多个content_for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆