如何从 Rails 实例变量渲染 HTML?
我有一个实例变量要传递给视图,@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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
答案不再正确了。 Rails 3 会自动为您转义 html,因此当您在控制器中:
这将输出 HTML 而不转义:
并且这两者都会转义 HTML:
The answer is not true anymore. Rails 3 automatically escapes html for you, so when you have in a controller:
This will output the HTML without escaping:
And both of this will escape the HTML:
如果
@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.