Rails 如何簡單的轉換 HTML 到 text
        
      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
        
        
              Categories:
            
            
                    
⟩
⟩
                  
                  
                    
⟩
⟩
                  
            
              Tags:
            
            
              Date:
            
            
              Published: 2017/05/26 - Updated: 2019/05/02
            
          
              Total: 224 words
          
      
              Like
              
              or Dislike
              
            
          About the Author
          很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯
        More to explore
      
       
 
 
 
 
 
 
 

轉換 HTML 到 一般網頁上可以顯示的純文字... 簡單?
其實,很不容易的,一般用 Rails 內建的 Strip_tags 以為就好,但是會碰到跳脫文字的問題:& > < ...
很多網路上的建議是用 gsub,不錯用,但是,又是要很大的一段 code,我剛發現一個很好用的方法:
以 "<p>test & test</p>" 這個最簡單的 HTML 來試試:
看到沒,夠簡單吧,其實只要用內建的truncate,完美的轉換 HTML 到 text!
那如果要在 controller 或是 model 中,轉換 HTML 到 text 呢?也很簡單,只是,這時你就要呼叫 ActionView 中的功能,以下就是轉換的呼叫方式:
就這樣,你就可以在 controller 或是 model 中呼叫 rails view 功能了,同時,你也可以在 Rails console 中驗證了。