避免使用HTML字符串 [英] Unescaping HTML string

查看:157
本文介绍了避免使用HTML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 & 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。



我试过以下内容:


  1. <%= the_string.html_safe%> #类型错误$ c>#呈现字符串不变
  2. 错误'can not dup NilClass'
  3. <%= CGI.unescapeHTML(the_string).html_safe%> #与错误类型错误'无法重复NilClass'

  4. <%= raw the_string%> #呈现字符串不变

如何将此字符串呈现为HTML?

解决方案正如你似乎已经注意到的那样,你需要处理两件事:


  1. 解开HTML实体

  2. 在您的视图中打印原始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):

 &lt;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\"&gt;\n&lt;/iframe&gt;

I am rendering it in an erb template like this:

<%= the_string %>

At the moment it renders as text like this:

&lt;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"&gt;&lt;/iframe&gt;

I need to render it as HTML.

I have tried the following:

  1. <%= the_string.html_safe %> # Renders the string unchanged
  2. <%= CGI.unescapeHTML(the_string) %> # Errors with a Type Error 'can't dup NilClass'
  3. <%= CGI.unescapeHTML(the_string).html_safe %> # Errors with a Type Error 'can't dup NilClass'
  4. <%= 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:

  1. Unescaping the HTML entities
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆