Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails truncate helper with link as omit text

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

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

The problem is that I want to use more as a clickable link so in theory I could use this:

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

Omission text is handled as unsafe so it's escaped. I tried to make it html_safe but it didn't work, instead of link [more] my browser is still showing the html for that link.

Is there any way to force truncate to print omission link instead of omission text?

like image 336
Jakub Troszok Avatar asked Feb 17 '11 17:02

Jakub Troszok


4 Answers

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
like image 84
Pan Thomakos Avatar answered Nov 12 '22 21:11

Pan Thomakos


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", "#" 
}
like image 31
Adam Rubin Avatar answered Nov 12 '22 20:11

Adam Rubin


Dirty solution... use the method "raw" to unescape it.
you have to be sure of "sanity" of your content.

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

raw is a helper acting like html_safe .
bye

edit: is not the omission of being escaped , but the result of truncate method.

like image 7
andrea Avatar answered Nov 12 '22 20:11

andrea


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.

like image 4
saneshark Avatar answered Nov 12 '22 20:11

saneshark