2015-09-14 33 views
0

我繼續我的博客應用程序的實現,我正在使用markdown(redcarpet gem)創建文章。如何清理博客文章預覽HTML實體 - Rails

在我的測試後,但是我有這樣的代碼

#This is a test post 

`<p> your paragraph text here </p>` 

寫在降價。

,並在我的後視圖我有這個

<div class="col-md-6"> 
    <% @posts.each do |post| %> 
    <div class="panel panel-default"> 
     <div class="panel-heading"> 
     <h3 class="panel-title"><%= link_to post.title, blog_post_path(post) %></h3> 
     </div> 
     <div class="panel-body"> 
     <%= truncate(strip_tags(post.html), length: 80) %> 
     </div> 
    </div> 
    <% end %> 
</div> 

的事情是,當我想要去除從降價到HTML轉換的HTML標籤,我在符號<的地方HTML實體>因此,我得到下面的輸出

This is a test post &lt;p&gt; your paragraph text here &lt;/p&gt; 

是否有解決方法嗎?我會爲<,>符號留在這種情況下還是應該只是有一些介紹,只有普通字符。

另外還有一個問題:有沒有一種方法來定位我在預覽中顯示的帖子的哪一部分?

+0

您使用的是哪個版本的Rails?帶有最近版本的Rails的'strip_tags'將特殊字符轉換爲html實體時出現了一個錯誤。 – MarsAtomic

+0

我正在使用4.2.1。這個版本里面有bug嗎? –

回答

1

Rails 4.2引入了HTML清理程序方法的新實現(其中一個是幫助程序strip_tags)。有一次,HTML標記通過正則表達式被刪除,Rails 4.2通過使用Nokogiri(通過絲瓜絡)實現了同樣的事情。

這似乎是一些向後兼容性丟了,因爲strip_tagsseems to behave differently under Rails 4.2比以前的版本,所以解決方法是使用sanitize幫手,而不是strip_tags

相反的:

<%= truncate(strip_tags(post.html), length: 80) %> 

使用:

<%= truncate(sanitize(post.html), length: 80) %> 

的助手的sanitize應該使用WhiteListSanitizer,但如果它不工作,你可以嘗試直接調用具體方法使用:

<%= truncate(Rails::Html::WhiteListSanitizer.new.sanitize(post.html), length: 80) %>