Alex Rivera | Logout

How to wrap content in html in a Rails helper

Asked 2011-03-10T00:51:46.857
9

I want to wrap some content in HTML in a Rails 3 helper so that in my view I can do this:

<%= rounded_box do-%>
  <%= raw target.text %>
<% end -%>

I have a helper method that looks like this:

def rounded_box(&block)
  str = "<div class='rounded_box'><div class='rounded_box_content'><div class='rounded_box_top'></div>        
  str << yield
  str << "<div class='rounded_box_bottom'><div></div></div></div>"
  raw str
end

The way I have it now returns the content properly wrapped in the HTML string, but not before rendering any erb in the rounded_box block (e.g. in this case the target.text is rendered twice, once wrapped, once not).

Is there a better way to do this? For simplicity, I'd like to avoid using content_tag, but if that's the only/best way I can do that.

Edit
Report

1 Answer

18

Call capture on the block instead of yield:

def rounded_box(&block)
  str = "<div class='rounded_box'><div class='rounded_box_content'><div class='rounded_box_top'></div>"        
  str << capture(&block)
  str << "<div class='rounded_box_bottom'><div></div></div></div>"
  raw str
end
answered 2011-03-10T00:59:45.680

Your Answer