DEV Community

Shivashankar
Shivashankar

Posted on

Gem to truncate HTML strings efficiently ...

Generally we use truncate view helper to truncate the text.

But it has an issue that it truncate the html tag as well and in worst case, a partial html tag gets truncated.

For example:

truncate("The Rails philosophy includes two major guiding principles: <strong>Don't Repeat Yourself:</strong>", length: 7
0)

It gives output as

"The Rails philosophy includes two major guiding principles: &lt;strong..."

It is not the desired output we want. Reason is it breaks the html tags.

truncato gem comes as a rescue for handling this one. This Gem performs well while comparing to other Gems in truncating the html content, which is additional advantage of using this one.

This is how truncato gives output

Truncato.truncate("The Rails philosophy includes two major guiding principles: <strong>Don't Repeat Yourself:</strong>", max_len
gth: 70)
"The Rails philosophy includes two major guiding principles: <strong>Do...</strong>"

The HTML tag is smartly retained here even though it truncate the text with in it.

Top comments (0)