在助手中渲染 content_for 块
我正在尝试通过助手呈现 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) 来渲染它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想查看 capture 以获取字符串中的输出,然后使用它。操作方法如下: http://api.rubyonrails.org/类/ActionView/Helpers/CaptureHelper.html#method-i-capture
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