Rails truncate helper with link as omit text

前端 未结 7 1867
忘掉有多难
忘掉有多难 2021-02-06 01:27

I\'m quite long description that I want to truncate using truncate helper. So i\'m using the:

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


        
相关标签:
7条回答
  • 2021-02-06 01:42

    I would suggest doing this on your own in a helper method, that way you'll have a little more control over the output as well:

    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 讨论(0)
  • 2021-02-06 01:46

    TextHelper#truncate has a block form of truncate, which lets you use a link_to that isn't escaped, while still escaping the truncated text:

    truncate("<script>alert('hello world')</script>") { link_to "Read More", "#" }
    
    #=> &lt;script&gt;alert(&#39;hello world&#39;...<a href="#">Read More</a>
    
    0 讨论(0)
  • 2021-02-06 01:47

    The only one that worked for me :

    <%= truncate(@article.content, length: 200, omission: " ... %s") % link_to('read more', article_path(@article)) %>
    
    0 讨论(0)
  • 2021-02-06 01:47

    I had the same problem, in my case i just used :escape => false. That worked:

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

    From documentation :

    The result is marked as HTML-safe, but it is escaped by default, unless :escape is false.... link: http://apidock.com/rails/ActionView/Helpers/TextHelper/truncate

    0 讨论(0)
  • 2021-02-06 01:56

    With Rails 4, you can/should pass in a block for the link:

    truncate("Once upon a time in a world far far away", 
      length: 10, 
      separator: ' ', 
      omission: '... ') {     
        link_to "Read more", "#" 
    }
    
    0 讨论(0)
  • 2021-02-06 01:59

    I encountered a similar situation and this did the trick. Try (line breaks for readability):

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

    You can use h to ensure sanity of article description, and since you are setting the link_to to a path you know to not be something potentially nefarious, you can mark the resulting string as html_safe without concern.

    0 讨论(0)
提交回复
热议问题