How to sanitize html string except image url?

爷,独闯天下 提交于 2019-12-10 21:53:26

问题


I'm trying to sanitize an html string, but I want to whitelist image urls. My code:

ActionView::Base.full_sanitizer.sanitize(phrase.meaning, tags: %w(img), attributes: %w(src))

This doesn't work, because it deletes all html tags and the value of src.

My expected result in a json file:

meaning: "Lorem ipsum.... http://localhost/image1.jpg .... Lorem ipsum"

回答1:


Perhaps it is easier to use the PermitScrubber from the same gem directly:

html = 'Foo <img src="foo" title="bar"> <a href="foo">bar</a> blob'
scrubber = Rails::Html::PermitScrubber.new
scrubber.tags = ['img']
html_fragment = Loofah.fragment(html)
html_fragment.scrub!(scrubber)
html_fragment.to_s
#=> "Foo <img src=\"foo\" title=\"bar\"> bar blob"


来源:https://stackoverflow.com/questions/35772712/how-to-sanitize-html-string-except-image-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!