如何在 Rails 助手中将 html 内容包装起来
我想将一些内容包装在 Rails 3 帮助程序中的 HTML 中,以便在我看来我可以这样做:
<%= rounded_box do-%>
<%= raw target.text %>
<% end -%>
我有一个如下所示的帮助程序方法:
def rounded_box(&block)
str = "<div class='rounded_box'><div class='rounded_box_content'><div class='rounded_box_top'></div>
str << yield
str << "<div class='rounded_box_bottom'><div></div></div></div>"
raw str
end
我现在的方式返回正确包装在 HTML 字符串中的内容,但是不在渲染 rounded_box 块中的任何 erb 之前(例如,在本例中, target.text 被渲染两次,一次包装,一次不包装)。
有更好的方法吗?为简单起见,我想避免使用 content_tag,但如果这是我能做到的唯一/最好的方法。
I want to wrap some content in HTML in a Rails 3 helper so that in my view I can do this:
<%= rounded_box do-%>
<%= raw target.text %>
<% end -%>
I have a helper method that looks like this:
def rounded_box(&block)
str = "<div class='rounded_box'><div class='rounded_box_content'><div class='rounded_box_top'></div>
str << yield
str << "<div class='rounded_box_bottom'><div></div></div></div>"
raw str
end
The way I have it now returns the content properly wrapped in the HTML string, but not before rendering any erb in the rounded_box block (e.g. in this case the target.text is rendered twice, once wrapped, once not).
Is there a better way to do this? For simplicity, I'd like to avoid using content_tag, but if that's the only/best way I can do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在块上调用
capture
而不是yield
:Call
capture
on the block instead ofyield
:将
<%= raw target.text %>
更改为<% raw target.text %>
,ERB 应该处理其余的事情。您不需要显式输出介入 ERB 标记的结果,因为它已由帮助程序处理。Change
<%= raw target.text %>
to<% raw target.text %>
, and ERB should handle the rest. You don't need to explicitly output the result of the intervening ERB tag, because it's been handled by the helper.