Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 301
iHiD Avatar asked Jul 21 '11 19:07

iHiD


1 Answers

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

like image 172
Sohan Avatar answered Oct 12 '22 22:10

Sohan