Garbage Burrito

Embedded Blocks for Rails Erb Tag Voodoo

Embedded Blocks for Rails Erb Tag Voodoo
Ben Kittrell - 04/23/2007 14:41:00
Comments: 2
Last Comment: 08/13/2009 13:57:05
Whilst upgrading doodlekit, I found a cool trick that I’ll probably start to use a lot.  I already posted about how to use blocks to make sort of custom tag in Rails.  I recently used this to clean up some html that had somehow creeped it’s way onto every view in Doodlekit .  I abstracted this view using a partial and a helper, so I can say….

  <% content_headers “Blog” do %>
    Some funky jazz
  <% end %.


…and it will wrap the content with an set of divs.  Pretty basic.

  def content_headers(header = '', sub_header = '', options = {}, &block)
    if !options.has_key?(:if) || options[:if]
      content_body = capture(&block)
      concat(render(:partial => 'shared/content_headers',
        :locals => { :body => content_body, :header => header, :sub_header => sub_header }),
        block.binding)
    end

  end

and the partial

  <!-- Lots of Heath's funky divs.... -->
  <div>
    <h2><%= header %></h2>
    <% unless sub_header.blank? -%>
      <h4><%= sub_header %></h4>
    <% end -%>
  </div>

  <%= body %>

  <!-- more divs and stuff.... -->


But then I needed the ability to pass a larger block of html to the helper, but I didn’t feel comfortable passing as an argument, ala

  <% content_headers “Blog”, link_to(“Blog”, :action => ‘index’) + “ &gt; #{@entry.title}“do %>

So what I did was create another helper that looks like this.

  <% content_headers “Blog” do %>
    <% breadcrumb do %>
      <%= link_to(“Blog”, :action => ‘index’) %> &gt;  <%= @entry.title} %>
    <% end %>
    Some funky jazz
  <% end %>


All the breadcrumb helper does is capture the block and set it to an instance variable called @breadcrumb.

  def breadcrumb(&block)
    @breadcrumb = capture(&block)
  end

Then I can display the breadcrumb instance variable anywhere I want in the content_headers partial.

  <!-- Lots of Heath's funky divs.... -->
  <div>
    <% if @breadcrumb -%>
      <div class="bread_crumb"><%= @breadcrumb %></div>
    <% end -%>
    <h2><%= header %></h2>
    <% unless sub_header.blank? -%>
      <h4><%= sub_header %></h4>
    <% end -%>
  </div>

  <%= body %>

  <!-- more divs and stuff.... -->


One way I’ll probably start to use this is to be able to define a small block of HTML in the view, that’s extracted and placed into the outer layout.

Lot’s of possibilities here.

Comments: 2
Last Comment: 08/13/2009 13:57:05

Comments

1. Aze   |   10/17/2008 10:42:24

Nice.

2. Tom  |  my website   |   08/13/2009 13:57:05

Hmm, correct me if I am wrong, but isn't this what content_for kind of does?

Post a Comment


Are you human? Please enter the word below.
M2dvbgquanbnmti2odmyotcynw==


powered by Doodlekit™ Free Website Builder by Doodlebit™ Website Company