Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple content_for on the same page

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.

like image 605
Jason Yost Avatar asked Apr 12 '11 06:04

Jason Yost


3 Answers

In Rails 4, you can pass the :flush parameter to override content.

<%= content_for :block_head, 'hello world', :flush => true %>

or, if you want to pass a block,

<%= content_for :block_head, :flush => true do %>
  hello world
<% end %>

cf. this helper's source code for more details

like image 66
danlee Avatar answered Nov 06 '22 01:11

danlee


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

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.

like image 39
Roman Avatar answered Nov 06 '22 02:11

Roman


You can always just pass the content directly and not rely on a block:

<% content_for :replaced_not_appended %>
like image 2
jmitchtx Avatar answered Nov 06 '22 02:11

jmitchtx