开发者

How to wrap content in html in a Rails helper

开发者 https://www.devze.com 2023-02-15 18:06 出处:网络
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-%>

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_bo开发者_开发百科x 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.


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


Change <%= raw target.text %> to <% raw target.text %>, and ERB should handle the rest. You don't need to explicitly output the result of the intervening ERB tag, because it's been handled by the helper.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号