Ruby on Rails 문자열에서 html 제거
루비와 레일즈에서 일하고 있는데, 옷을 벗을 방법이 있나요?htmlsanitize 또는 equal 메서드를 사용하여 문자열에서 텍스트만 입력 태그의 내부 값 속성으로 유지하시겠습니까?
우리가 이것을 모델에 사용하고 싶다면,
ActionView::Base.full_sanitizer.sanitize(html_string)
이것은 "sys_discovery" 방법의 코드입니다.
이 있습니다.strip_tags의 방법.ActionView::Helpers::SanitizeHelper:
http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-strip_tags
편집: 값 속성 내의 텍스트를 가져오기 위해, 노코기리와 같은 것을 Xpath 표현식과 함께 사용하여 문자열에서 가져올 수 있습니다.
ActionView::Base.full_sanitizer.sanitize(html_string)
태그 및 특성의 화이트리스트는 다음과 같이 지정할 수 있습니다.
ActionView::Base.full_sanitizer.sanitize(html_string, :tags => %w(img br p), :attributes => %w(src style))
위 문에서는 태그 img, 브랜드 p 및 속성 src 및 스타일을 사용할 수 있습니다.
예, 다음과 같이 부릅니다.sanitize(html_string, tags:[])
Loofah 라이브러리는 HTML과 XML(문서와 문자열 조각 모두)에 적합하기 때문에 사용해 왔습니다.이것은 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 "
사용할 수 있는 모든 HTML 태그를 제거하려면
htm.gsub(/<[^>]*>/,'')
이건 어때?
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
이것은 레일 6.1.3에서 작동합니다.
.errors-description
= sanitize(message, tags: %w[div span strong], attributes: %w[class])
HTML의 출처:ActionText,할수있습니다.to_plain_text:
@my_string = <p>My HTML String</p>
@my_string.to_plain_text
=> My HTML String
https://www.rubydoc.info/github/rails/rails/ActionText%2FContent:to_plain_text
언급URL : https://stackoverflow.com/questions/7414267/strip-html-from-string-ruby-on-rails
'programing' 카테고리의 다른 글
| UI 이미지를 가져와서 검은색 테두리를 지정하려면 어떻게 해야 합니까? (0) | 2023.06.03 |
|---|---|
| Android: 키보드 입력 버튼을 "검색"이라고 말하고 클릭을 처리하는 방법은 무엇입니까? (0) | 2023.06.03 |
| Swift에서 NSDocument Directory를 찾는 방법은 무엇입니까? (0) | 2023.06.03 |
| Android 응용 프로그램에서 인터넷에 액세스하려면 어떤 권한이 필요합니까? (0) | 2023.06.03 |
| 패키지의 로컬 종속성입니다.제이손 (0) | 2023.06.03 |