如何直接输出在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不会将别人的工作归功于自己,而是直接指出您这里。
Rather than take credit for someone else's work, I'll just point you here.
这篇文章提供了更好的答案,虽然并不完全令人满意。
基本上,您必须设置要放置 HTML 的变量,然后在助手内操作它。
这可能在 Rails 中不起作用,但是您尝试做的事情应该在 Rails 中起作用。 Rails 使用 Erubi 引擎的子类来特殊处理此语法以使其正常工作。
This post provides a better answer, though not entirely satisfying.
Basically, you have to set the variable into which HTML is being placed, then manipulate that inside your helper.
This is likely not going to work in Rails, however what you are trying to do should work in Rails. Rails uses a subclass of Erubi's engine to special-case this syntax to make it work.