简体   繁体   English

如何解析链接并转义html实体?

[英]How to parse links and escape html entities?

I have some user provided content that I want to render. 我有一些用户提供的内容要渲染。

Obviously the content should be escaped, rails does this by default. 显然,内容应转义,Rails默认情况下会这样做。 However I also want to parse the text so that urls are presented as links. 但是,我也想解析文本,以便将URL显示为链接。

There is an auto_link helper which does just that. 有一个auto_link助手可以做到这一点。 However no matter what order I do this in I can't get the desired result. 但是,无论我按什么顺序进行操作,都无法获得理想的结果。

Take content: 取得内容:

content                                             
  => "<img src=\"foo\" />\\r\\n\\r\\nhttp://google.com"

If this is escaped, because the slashes in the url are escaped, auto_link will not work: 如果对此进行了转义,因为url中的斜杠已转义,则auto_link将不起作用:

Rack::Utils.escape_html(content)                    
  => "&lt;img src=&quot;foo&quot; &#x2F;&gt;\\r\\n\\r\\nhttp:&#x2F;&#x2F;google.com"

If I use auto_link first obviously the link will be escaped. 如果我先使用auto_link,显然链接将被转义。 Additionally auto_link strips unwanted content rather than escaping. 另外,auto_link会删除不需要的内容,而不是转义。 If a script tag is present in the input I want it escaped not removed. 如果输入中存在脚本标记,则希望它转义而不删除。

auto_link(content)                                  
  => "<img src=\"foo\" />\\r\\n\\r\\n<a href=\"http://google.com\">http://google.com</a>"

Any idea how to do get the desired output? 任何想法如何获得所需的输出?

Thanks for any help. 谢谢你的帮助。

You could strip out all the escaped whitespace characters with content.gsub!(/\\\\./, "") . 您可以使用content.gsub!(/\\\\./, "")所有转义的空白字符。 Then you'll be able to use auto_link . 然后,您将可以使用auto_link

我最终使用的解决方案是放弃auto_link,让Rack转义我的内容服务器端,然后使用https://github.com/gabrielizaias/urlToLink在客户端的文本中解析出链接

$('p').urlToLink();

我在以下方面取得了成功:

auto_link(h(content))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM