我继承了以下字符串(我对格式无能为力):
<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>
我在这样的 erb 模板中呈现它:
<%= the_string %>
目前它呈现为这样的文本:
<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>
我需要将其呈现为 HTML。
我尝试了以下方法:
-
<%= the_string.html_safe %>
# 呈现字符串不变 -
<%= CGI.unescapeHTML(the_string) %>
# 类型错误 'can't dup NilClass' 的错误 -
<%= CGI.unescapeHTML(the_string).html_safe %>
# 类型错误 'can't dup NilClass' 的错误 -
<%= raw the_string %>
# 呈现字符串不变
如何将此字符串呈现为 HTML?
最佳答案
您似乎已经注意到,您需要注意两件事:
- 取消转义 HTML 实体
- 在您的 View 中打印原始 html
对于数字 2 <%= raw ... %>
应该可以正常工作。
对于数字 1 CGI.unescapeHTML
是个正确的主意,但我认为它无法识别所有 HTML 实体,因此我建议您查看 HTML Entites gem
您也可以尝试使用 simple_format helper 方法,但我认为您将不得不向它传递一些选项以允许 <iframe>
标签
另外,我强烈建议移动您的 unescaping
将逻辑转化为辅助方法。
关于html - 取消转义 HTML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10677908/