【问题标题】:Rendering a content_for block in a helper在帮助程序中渲染 content_for 块
【发布时间】:2011-10-10 12:26:24
【问题描述】:

我正在尝试通过帮助程序呈现 content_for 块的结果。

我有一个模板 (HAML) 和如下布局:

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

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

这绝对没问题。

我想要做的是在一个助手中进行调用。所以我的目标是:

# 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
....

我可以通过调用助手来获得部分结果:

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

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

但这对我来说很难看。

有什么想法吗?提前致谢。

回答:再次使用 content_for(:page_header) 来渲染它。

【问题讨论】:

    标签: ruby-on-rails templates helpers


    【解决方案1】:

    您可能想查看捕获以获取字符串中的输出,然后使用它。方法如下:http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-capture

    【讨论】:

    • 感谢您的回答。这为我指明了正确的解决方案,即再次使用 content_for 来呈现内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 2011-04-07
    • 1970-01-01
    • 2014-06-02
    • 2021-05-10
    相关资源
    最近更新 更多