Rails 如何转义并显示渲染视图的内容
我试图在文本区域中显示 Rails 视图文件。视图文件包含一堆 HTML,我想转义它,这样它就不会干扰页面 html。这是一个例子:
In this view we are going to display the contents of a partial
<textarea>
<%= html_escape render('partial') %>
</textarea>
在partial.html.erb中我会遇到
Hello this is partial.html.erb and this is a
<textarea>textarea</textarea> blah blah blah.
问题是:partial.html中的textarea破坏了第一个视图中的textarea,因为它没有被html_escaped。如何属性转义并显示文本区域内部分的内容?
I am trying to show a rails view file in a textarea. the view file contains a bunch of HTML, which I want to escape so that it does not interfere with on page html. here is an example:
In this view we are going to display the contents of a partial
<textarea>
<%= html_escape render('partial') %>
</textarea>
and in partial.html.erb I would have
Hello this is partial.html.erb and this is a
<textarea>textarea</textarea> blah blah blah.
The problem is: the textarea in partial.html is breaking the textarea in the first view because it is not being html_escaped. How do I property escape and display the contents of the partial inside the textarea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你尝试过使用
Did you try using
尝试在控制器中使用
render_to_string
,然后使用生成的字符串上的html_escape
。Try
render_to_string
in your controller and then usinghtml_escape
on the resulting string.好吧 - 我想通了。您基本上必须调用 render 两次。第一次是渲染文件,第二次是转义渲染的文件。这太丑了!
我很想看看是否还有其他人有其他方法来转义partial.html。
Ok - I figured it out. You basically have to call render twice. The first time is to render the file and the second time is to escape that rendered file. This is ugly!
I'd be interested to see if anyone else has any other ways to escape partial.html.
你好
我看到这是很久以前的事了,但我的建议是:
... 清理 instance.yourtext %>
我在 S.Ruby、D.Thomas 和 D.Hansson 的“Agile web design with Ruby on Rails”中找到了“清理”助手。
希望它有帮助...
Hello
I see it was long time ago , but here what I suggest :
... sanitize instance.yourtext %>
I found the 'sanitize' helper in the "Agile web design with Ruby on Rails" by S.Ruby , D.Thomas and D.Hansson .
Hope it helps...
已编辑
默认情况下,Rails 中的 text_area 会转义 HTML 以避免恶意脚本嵌入。使用表单助手创建
注意:如果您需要在文本区域中查看原始 HTML,只需包含 :escape 参数并将值设置为 false 以禁用 HTML 转义。
引用: http://api.rubyonrails.org/classes /ActionView/Helpers/FormTagHelper.html#method-i-text_area_tag
如果使用此功能,如果源不可信或不向公众开放,我建议验证或删除提交值中的脚本标记。
EDITED
By default in Rails, text_area escapes HTML to avoid malicious script embedding. Use a form helper to create your
<textarea>
Note: If you one needs to see the raw HTML in the text area, just include the :escape parameter and set the value to false to disable HTML escaping.
Citation: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-text_area_tag
If using this feature, I recommend validating or eliminating the script tag from the submitted value if the source is not trusted or open to the public.