Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap content in html in a Rails helper

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.

like image 638
Marcus Avatar asked Mar 10 '11 00:03

Marcus


1 Answers

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
like image 128
Jakub Hampl Avatar answered Oct 03 '22 04:10

Jakub Hampl