Home Play Pinja Bobbity flop

A blog about Ruby, Rails and other Tech. Mostly.

Back to blog

9th Aug 2007, 8:50am
Rails: wrapping content from a helper

The form_tag method in ActionView uses a nice trick to wrap a block of content in form tags, and you can wrap content the same way yourself.

You want to write something like:

<% yellow_boxed do %>
some text and html and stuff
it's probably only worth doing it this way
if this bit is longer than a line or two
<% end %>
This reads in a very natural way. To do this, I have a helper method called yellow_boxed:
  def yellow_boxed(&block)
    concat(render(:partial=>"yellow_boxtop"), block.binding)
    content = capture(&block)
    concat(content, block.binding)
    concat(render(:partial=>"yellow_boxbottom"), block.binding)
This technique can be used in any situation where it is logical to wrap content.

Note that I render a partial for the top and the bottom of my yellow box. The partials just contain table, tr and td tags and so on, but I wanted to keep the html strings out of my helper. But for short lengths of html it's not a problem, you can put text strings there instead of the much more expensive calls to render.

Back to blog