简体   繁体   中英

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(&block)

    # 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM