如何从 Rails 实例变量渲染 HTML?

发布于 2024-09-06 22:24:49 字数 185 浏览 10 评论 0原文

我有一个实例变量要传递给视图,@body

@body 是一个包含 html 的字符串。

<%= @body %> 渲染字符串,而不是 html。如何渲染字符串中的 html?

可能的?

提前致谢!

I have an intstance variable I am passing to a view, @body.

@body is a string with html in it.

<%= @body %> renders the string, not the html. How do I render the html in the string?

Possible?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

dawn曙光 2024-09-13 22:24:49

答案不再正确了。 Rails 3 会自动为您转义 html,因此当您在控制器中:

@error = "<h1>OMG u broke teh intertubez!!111</h1>"

这将输出 HTML 而不转义:

<%= raw @error %>

并且这两者都会转义 HTML:

<%= h @error %>
<%= @error %>

The answer is not true anymore. Rails 3 automatically escapes html for you, so when you have in a controller:

@error = "<h1>OMG u broke teh intertubez!!111</h1>"

This will output the HTML without escaping:

<%= raw @error %>

And both of this will escape the HTML:

<%= h @error %>
<%= @error %>
明媚如初 2024-09-13 22:24:49

如果 @body 中有一些 html,<%= @body %> 会输出一些 html。
在该变量中包含 html 有点奇怪,因为控制器不应该传递任何 HTML(控制器必须与视图无关)。

这就是为什么我们有一些辅助方法。
创建一个生成一些 html 的辅助方法,并在您的视图中使用它。

<%= @body %> would output some html if you had some html in @body.
It's a little weird to have html in that variable since the controller is not supposed to pass any HTML (The controller has to be view agnostic).

This is why we have some helper methods.
Make a helper method that generates some html, and use it in your view.

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