Reputation: 871
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 ) %>
Upvotes: 5
Views: 3522
Reputation: 732
This might be late but useful to someone else. This worked for me.
<%= truncate(myString, escape: false, length: 20 ) %>
Upvotes: 1
Reputation: 1032
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’s New Laptop"
> truncate(simple_format(myString), escape: false)
> => "<p>Apple’s New Laptop..."
> truncate(simple_format(myString), escape: false, length: 19)
> => "<p>Apple’s..."
This has the potential to create unbalanced HTML tags by cutting the </p>
for example, so use carefully.
Upvotes: 3
Reputation: 3880
There was something changed in the truncate-helper in Rails 4. The documentation does tells us:
The result is marked as HTML-safe, but it is escaped by default, unless :escape is false.
http://apidock.com/rails/v4.0.2/ActionView/Helpers/TextHelper/truncate
Rails normally escapes all strings. If you just want to put some unicode chars in strings in your code, you can do it by using the \u notation with the hexadecimal code. Then truncate will also count the char as exactly one char.
myString = "Apple\u2019s New Laptop"
Upvotes: 1