如何直接输出在 ERB 中获取块的 helper 的结果?
我有一个需要块的助手:
def container(&block)
render(:partial => 'layouts/container', :locals => {:content => capture(&block)})
end
当我尝试在 ERB 中的 <%= ... %>
标记内使用它时:
<%= container do %>
Test
<% end %>
我收到一个编译错误
:
compile error
test2.html.erb:1: syntax error, unexpected ')'
old_output_buffer = output_buffer;;@output_buffer = ''; __in_erb_template=true ; @output_buffer.concat(( container do ).to_s); @output_buffer.concat "\r\n"
^
test2.html.erb:4: syntax error, unexpected kENSURE, expecting ')'
test2.html.erb:6: syntax error, unexpected kEND, expecting ')'
但是,如果我捕获助手的输出然后输出它:
<% output = container do %>
Test
<% end %>
<%= output %>
它工作正常,但很难看。
有什么办法可以做我想做的事吗? (注意:通常我使用 HAML,但我试图让我的助手为团队中目前仍在 ERB 工作的其他人工作;切换到 HAML 不是一个解决方案)。
I have a helper that takes a block:
def container(&block)
render(:partial => 'layouts/container', :locals => {:content => capture(&block)})
end
When I try to use it inside a <%= ... %>
tag in ERB:
<%= container do %>
Test
<% end %>
I get a compile error
:
compile error
test2.html.erb:1: syntax error, unexpected ')'
old_output_buffer = output_buffer;;@output_buffer = ''; __in_erb_template=true ; @output_buffer.concat(( container do ).to_s); @output_buffer.concat "\r\n"
^
test2.html.erb:4: syntax error, unexpected kENSURE, expecting ')'
test2.html.erb:6: syntax error, unexpected kEND, expecting ')'
However, if I capture the output of the helper and then output it:
<% output = container do %>
Test
<% end %>
<%= output %>
it works fine, but is ugly.
Is there any way to do what I'd like to? (Note: usually I use HAML, but I'm trying to get my helper working for someone else on the team who is still working in ERB for now; switching to HAML isn't a solution).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

我不会将别人的工作归功于自己,而是直接指出您这里。
Rather than take credit for someone else's work, I'll just point you here.