开发者

Rendering a content_for block in a helper

I'm trying to render the result of a content_for block through a helper.

I have a template (HAML) and a layout as follows:

# app/views/books/show.html.haml
-content_for(:page_header) do
     %h1= @book.title

# app/views/application.html.haml
...
=yield(:page_header) 
...

That works absolutely fine.

What I want to do is make that call in a helper instead. So I'm aiming for the following:

# app/views/books/show.html.haml
-content_for(:page_header) do
     %h1= @book.title

# app/views/application.html.haml
....
=page_header(block)
....

# app/helpers/application.rb
....
def page_header(&b开发者_StackOverflow社区lock)

    # Some view logic
    # ...

    =yield(:page_header)
end
....

I can achieve a partial result by calling the helper with:

# app/views/application.html.haml
=page_header { yield(:page_header) }

# app/helpers/application.rb
def page_header(&block)
  yield
end

but that feels ugly to me.

Any ideas? Thanks in advance.

ANSWER: Use content_for(:page_header) again to render it.


You might wanna look at capture to get the output in a string and then use it. Here's how: http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-capture

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜