Ruby on Rails 문자열에서 html 제거


121

Ruby on Rails로 작업하고 있습니다. htmlsanitize 또는 equal 메서드를 사용하여 문자열에서 제거 하고 입력 태그의 value 속성 안에 텍스트 만 유지하는 방법이 있습니까?


아니 살균 또는 동일하지만, text.strip작동
Keon은

답변:



183

이것을 모델에서 사용하려면

ActionView::Base.full_sanitizer.sanitize(html_string)

"strip_tags"메소드의 코드입니다.


31
이것은 작동하지만 mdoel에서 ActionView를 참조하는 것은 어색합니다. 더 깔끔하게 .NET을 사용 require 'html/sanitizer'하여 자체 새니 타이 저를 인스턴스화하고 인스턴스화 할 수 있습니다 HTML::FullSanitizer.new.
Nik Haldimann

8
@nhaldimann, require 'html/sanitizer'오류가 발생하므로 다음을 사용해야합니다. Rails::Html::FullSanitizer.new( edgeapi.rubyonrails.org/classes/HTML/… )
Linh Dam


24
ActionView::Base.full_sanitizer.sanitize(html_string)

태그 및 속성의 화이트리스트는 다음과 같이 지정할 수 있습니다.

ActionView::Base.full_sanitizer.sanitize(html_string, :tags => %w(img br p), :attributes => %w(src style))

위의 문은 img , brp 태그 와 srcstyle 속성을 허용합니다 .


9

HTML과 XML (문서와 문자열 조각 모두)에 적합하기 때문에 Loofah 라이브러리를 사용했습니다. 그것은 html sanitizer gem의 엔진입니다. 사용이 얼마나 간단한 지 보여주기 위해 코드 예제를 붙여 넣는 것입니다.

수세미 보석

unsafe_html = "ohai! <div>div is safe</div> <script>but script is not</script>"

doc = Loofah.fragment(unsafe_html).scrub!(:strip)
doc.to_s    # => "ohai! <div>div is safe</div> "
doc.text    # => "ohai! div is safe "

1

이건 어때요?

white_list_sanitizer = Rails::Html::WhiteListSanitizer.new
WHITELIST = ['p','b','h1','h2','h3','h4','h5','h6','li','ul','ol','small','i','u']


[Your, Models, Here].each do |klass| 
  klass.all.each do |ob| 
    klass.attribute_names.each do |attrs|
      if ob.send(attrs).is_a? String
        ob.send("#{attrs}=", white_list_sanitizer.sanitize(ob.send(attrs), tags: WHITELIST, attributes: %w(id style)).gsub(/<p>\s*<\/p>\r\n/im, ''))
        ob.save
      end
    end
  end
end

Rails::Html::FullSanitizer.new화이트리스트를 지정하지 않으려 는 경우도 있습니다.
프레드릭
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.