2011-02-17 20 views
10

我很長的描述,我想截斷使用truncate助手。 所以我使用的:Rails截斷助手鍊接爲遺漏文本

truncate article.description, :length => 200, :omission => ' ...' 

的問題是,我想使用更多的可點擊的鏈接所以理論上我可以使用這樣的:

truncate article.description, :length => 200, :omission => "... #{link_to('[more]', articles_path(article)}" 

遺漏文本作爲不安全的處理,這樣它逃脫了。我試圖使html_safe,但它沒有工作,而不是鏈接[更多]我的瀏覽器仍然顯示該鏈接的HTML。

有什麼辦法強制截斷打印省略鏈接,而不是遺漏文本?

+1

可能出現[在ruby中省略截斷鏈接](http:// stackoverflow。COM /問題/ 4964073 /補充遺漏 - 在 - 紅寶石截短的A-Link) –

回答

10

我建議在一個輔助方法對自己這樣做,這樣,你必須在輸出以及多一點控制:

def article_description article 
    output = h truncate(article.description, length: 200, omission: '...') 
    output += link_to('[more]', article_path(article)) if article.description.size > 200 
    output.html_safe 
end 
+0

@ PAM-Thomakos這exept一個問題的偉大工程。當我點擊鏈接時,它會轉到posts.1而不是post/1。 –

+0

它應該是奇異'article_path'代替複數'articles_path' – Patrick

+0

是什麼截斷前的'h'嗎? – Patrick

7

骯髒的解決方案......使用方法「生「來逃避它。
你必須確保你的內容「健全」。

raw(truncate article.description, :length => 200, :omission => "... #{link_to('[more]', articles_path(article)}") 

原料是像個html_safe一個幫手。
bye

編輯:不是遺漏被轉義,而是截斷方法的結果。

+1

的問題是,我不能肯定article.description的理智的 –

4

我遇到過類似的情況,這個伎倆。嘗試(換行符以提高可讀性):

(truncate h(article.description), 
        :length => 200, 
        :omission => "... #{link_to('[more]',articles_path(article)}") 
        .html_safe 

你可以用小時,以保證文章描述的理智,因爲你是在的link_to設定的路徑,你知道沒有什麼潛在的邪惡,你可以標記所產生的字符串作爲html_safe而不用擔心。

+0

你需要小心在'逃生經過:FALSE',至少像Rails 4.0.1,因爲['TextHelper#truncate'會添加其自己的轉義(https://github.com/rails/rails/blob/58ab79ff9b34c22c3477e29763fdd4f4612e938d/actionpack/lib/action_view/helpers/text_helper.rb#L92)至'H(article.description)級聯'和'遺漏'文本。沒有任何'.html_safe'會阻止它。 –

2

TextHelper#truncateblock form of truncate,它可以讓你使用沒有逃脫link_to,但仍逃脫被截斷的文本:

truncate("<script>alert('hello world')</script>") { link_to "Read More", "#" } 

#=> &lt;script&gt;alert(&#39;hello world&#39;...<a href="#">Read More</a> 
1

,對我的工作只有一個:

<%= truncate(@article.content, length: 200, omission: " ... %s") % link_to('read more', article_path(@article)) %> 
10

使用Rails 4,您可以/應該通過一個塊鏈接:

truncate("Once upon a time in a world far far away", 
    length: 10, 
    separator: ' ', 
    omission: '... ') {  
    link_to "Read more", "#" 
} 
+0

工程。謝謝.. – Abram

+0

這是爲我做。謝謝! – iamse7en

1

我有同樣的問題,在我的情況下,我只是使用:escape => false。 這工作:

truncate article.description, :length => 200, :omission => "... #{link_to('[more]', articles_path(article)}", :escape => false

從技術文檔:

結果被標記爲HTML安全的,但它在默認情況下逃脫,除非:逃避是假的.... 鏈接: http://apidock.com/rails/ActionView/Helpers/TextHelper/truncate