Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate & Simple Format String in Ruby on Rails

I am trying to take a string and render it with simple_format while at the same time truncating it. It works when I just use one or the other, but not when I do both. Why is this not doing simple_format and truncating simultaneously.

Controller

myString = "Apple’s New Laptop"

View

<%= simple_format truncate( myString, :length => 20 ) %>
like image 943
user2270029 Avatar asked Feb 16 '14 17:02

user2270029


1 Answers

The way to do this is to truncate after you have used simple_format on the string. Since truncate escapes the string by default, you have to use the escape: false option.

> myString = "Apple&#8217;s New Laptop"

> truncate(simple_format(myString), escape: false) 
> => "<p>Apple&#8217;s New Laptop..."

> truncate(simple_format(myString), escape: false, length: 19)
> => "<p>Apple&#8217;s..."

This has the potential to create unbalanced HTML tags by cutting the </p> for example, so use carefully.

like image 150
maxhm10 Avatar answered Oct 29 '22 17:10

maxhm10