Garbage Burrito

Rails: Capturing HTML in Erb Blocks

Rails: Capturing HTML in Erb Blocks
Ben Kittrell - 05 01, 2007 @ 03:24PM
Comments: 4

I've been having fun with blocks and HTML lately, but I realized I kind of glazed over a very important, yet enigmatic piece of the puzzle.  How do you capture the block of HTML, and append/prepend stuff to it?  To figure this out I had to dig a little.

I knew that the new and improved form_tag helper had to have this magic in it, and sure enough....

if block_given?
  content = capture(&block)
  concat(tag(:form, html_options, true) + method_tag, block.binding)
  concat(content, block.binding)
  concat("</form>", block.binding)
else
  tag(:form, html_options, true) + method_tag
end


First it checks to see if a block was provided.  If so we use the capture helper to grab the HTML from the enclosed block.  Capturing it means it ain't going to print to the screen itself.  Using the concat helper, we can "bind" new HTML to the output buffer.  This is a little confusing, because the arguments are kind of backwards, IMO.  Think of block.binding as the HTML page, and the first argument as the shtuff you want to append to it.

If there's no block, it just creates the first half of the form tag.  

Here's a simple example.  We needed to wrap all the forms in Doodlekit with a div, for HTML compliance or some other crazy CSS Wizardy.  So I overwrote the form_tag helper like this...

alias old_form_tag form_tag

def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &proc)
  if block_given?
    content = capture(&proc)
    concat('<div class="form_tag">', proc.binding)
    concat(old_form_tag(url_for_options, options, parameters_for_url), proc.binding)
    concat(content, proc.binding)
    concat('</form></div>', proc.binding)
  else
    old_form_tag(url_for_options, options, parameters_for_url)
  end
end


I alias the original form_tag method, so I can still use it.  If a block is given I capture the HTML.  Print the div, print the form, print the captured content, print the end form, print the end div.

It's a little less than straight forward at first, but once you've got it your good to rock some funky erb beats.

Tags: Rails, ruby
Comments: 4

Comments

1. xenon - 07 24, 2007 @ 09:20AM

Hi, where did you place the code starting with alias? I tried putting it in the application_helper.rb but it seems that it doesn't like the alias function. I tried a simpler version and if alias is present, it just doesn't work here. Any ideas?

2. Anonymous - 10 16, 2007 @ 12:24PM

nice

3. nala - 11 12, 2007 @ 11:17PM

Nice Site!

4. Seth - 07 09, 2008 @ 09:41PM

I've been looking all over for a nice succinct explanation. Thank yoU!!

Post a Comment




powered by : Doodlekit Online Free Website Builder : developed by : Doodlebit™ Website Company