user2270029
user2270029

Reputation: 871

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 ) %>

Upvotes: 5

Views: 3522

Answers (3)

Fatimah
Fatimah

Reputation: 732

This might be late but useful to someone else. This worked for me.

 <%= truncate(myString, escape: false, length: 20 ) %>

Upvotes: 1

maxhm10
maxhm10

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&#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.

Upvotes: 3

Meier
Meier

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

Related Questions