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 stuffit's probably only worth doing it this wayif 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)  end

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s