如何在 Rails 助手中将 html 内容包装起来

发布于 2024-10-21 10:17:19 字数 675 浏览 11 评论 0原文

我想将一些内容包装在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

执笔绘流年 2024-10-28 10:17:19

在块上调用 capture 而不是 yield

def rounded_box(&block)
  str = "<div class='rounded_box'><div class='rounded_box_content'><div class='rounded_box_top'></div>"        
  str << capture(&block)
  str << "<div class='rounded_box_bottom'><div></div></div></div>"
  raw str
end

Call capture on the block instead of yield:

def rounded_box(&block)
  str = "<div class='rounded_box'><div class='rounded_box_content'><div class='rounded_box_top'></div>"        
  str << capture(&block)
  str << "<div class='rounded_box_bottom'><div></div></div></div>"
  raw str
end
桜花祭 2024-10-28 10:17:19

<%= 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文