Rails 如何簡單的轉換 HTML 到 text

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
761   0  
·
2017/05/26
·
1 mins read


轉換 HTML 到 一般網頁上可以顯示的純文字... 簡單?

其實,很不容易的,一般用 Rails 內建的 Strip_tags 以為就好,但是會碰到跳脫文字的問題:& > < ...

很多網路上的建議是用 gsub,不錯用,但是,又是要很大的一段 code,我剛發現一個很好用的方法:

以 "<p>test &amp; test</p>" 這個最簡單的 HTML 來試試:

s="<p>test &amp; test</p>"
truncate(strip_tags(s), length: s.length)
> "test &amp;amp; test"
truncate(strip_tags(s), escape: false, length: s.length)
> "test &amp; test"

看到沒,夠簡單吧,其實只要用內建的truncate,完美的轉換 HTML 到 text!

那如果要在 controller 或是 model 中,轉換 HTML 到 text 呢?也很簡單,只是,這時你就要呼叫 ActionView 中的功能,以下就是轉換的呼叫方式:

ActionView::Base.full_sanitizer.sanitize(string_wtih_html_tag)

就這樣,你就可以在 controller 或是 model 中呼叫 rails view 功能了,同時,你也可以在 Rails console 中驗證了。


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

分類於:
標籤:
日期:
創作於:2017/05/26,最後更新於:2019/05/02。
合計:224字


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.