避免使用HTML字符串 [英] Unescaping HTML string
问题描述
& lt; iframe \\ \\ n class = \some_class \\\\
type = \text / html\\\\
src = \/embed/iframe_content.html?id=tsqA5D7_z10\\\\
width = \960 \\\\
height = \593 \\\\
marginwidth = \0 \\\\
marginheight = \0 \\\\
frameborder = \\ \\ 0\ &安培; GT; \\\
&安培; LT; / iframe中&安培; GT;
我将其渲染到像这样的erb模板中:
<%= the_string%>
目前它呈现为这样的文本:
& lt; iframe class =some_classtype =text / htmlsrc =/ embed / iframe_content.html?id = tsqA5D7_z10width =960height =593marginwidth =0marginheight =0frameborder =0& gt;& lt; / iframe& gt;
我需要将它呈现为HTML。
我试过以下内容:
-
<%= the_string.html_safe%>
#类型错误$ c>#呈现字符串不变 错误'can not dup NilClass' -
<%= CGI.unescapeHTML(the_string).html_safe%>
#与错误类型错误'无法重复NilClass' -
<%= raw the_string%>
#呈现字符串不变
如何将此字符串呈现为HTML?
- 解开HTML实体
- 在您的视图中打印原始html
对于数字2 < ;%= raw ...%>
应该可以正常工作。
对于数字1 CGI.un escapeHTML
是正确的想法,但我不认为它可以识别所有的HTML实体,所以我建议看一看 HTML Entites gem
您也可以尝试使用 simple_format 帮助程序方法,但我认为您将不得不通过它的一些选项来允许< iframe>
标记
我也强烈建议移动 unescaping
逻辑转换为辅助方法。
I have the inherited the following string (I can do nothing about the format):
<iframe \n class=\"some_class\"\n type=\"text/html\" \n src=\"/embed/iframe_content.html?id=tsqA5D7_z10\" \n width=\"960\" \n height=\"593\" \n marginwidth=\"0\" \n marginheight=\"0\" \n frameborder=\"0\">\n</iframe>
I am rendering it in an erb template like this:
<%= the_string %>
At the moment it renders as text like this:
<iframe class="some_class" type="text/html" src="/embed/iframe_content.html?id=tsqA5D7_z10" width="960" height="593" marginwidth="0" marginheight="0" frameborder="0"></iframe>
I need to render it as HTML.
I have tried the following:
<%= the_string.html_safe %>
# Renders the string unchanged<%= CGI.unescapeHTML(the_string) %>
# Errors with a Type Error 'can't dup NilClass'<%= CGI.unescapeHTML(the_string).html_safe %>
# Errors with a Type Error 'can't dup NilClass'<%= raw the_string %>
# Renders the string unchanged
How can I render this string as HTML?
As you seem to have noticed, there are two things you need to take care of:
- Unescaping the HTML entities
- Printing the raw html in your view
For number 2 <%= raw ... %>
should work fine.
For number 1 CGI.unescapeHTML
was the right idea, but I don't think it recognizes all HTML entities so I would recommend taking a look at the HTML Entites gem
You can also try and use the simple_format helper method, but I think you are going to have to pass it some options for it to allow the <iframe>
tag
also I would strongly suggest moving your unescaping
logic into a helper method.
这篇关于避免使用HTML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!