开发者

How does a helper method yield to a block in rails 3?

I have used this pattern for a number of helpers in rails 2, but it isn't working the same in rails 3. My goal is to have a helper method generate some html tags with content nested inside. Here is a basic example of what I'm trying to get:

<div class="box">
  my content
</div>

In rails 2 I do it like this:

inside my layout file I call the helper method:

  <% box_wrapper do %>
    <%= yield -%>
  <% end %>

The helper method is defined like this:

def box_wrapper
  concat <<-EOF.html_safe
    <div class="box">
  EOF

  yield  if block_given?
  concat <<-EOF.html_safe
    </div>
  EOF
end

But in rails 3 when the view gets rendered it outputs my entire page and then开发者_Go百科 inside the box_wrapper it renders all of the page content a 2nd time.

I think I'm missing something obvious with how to use helpers and yields. Any ideas?


In Rails 3, you no longer need to use the concat method to build the content of your blocks.

Your helper now looks like this:

def box_wrapper(&block)  
  content = capture(&block)  
  content_tag(:div, content, :class => 'box')  
end

You can see other examples in Railscasts 208.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜