简体   繁体   中英

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. However I also want to parse the text so that urls are presented as links.

There is an auto_link helper which does just that. 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:

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. Additionally auto_link strips unwanted content rather than escaping. 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!(/\\\\./, "") . Then you'll be able to use auto_link .

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

$('p').urlToLink();

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

auto_link(h(content))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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