I have this html text:
<p> I'm a html text</p>
To show it on my web page, I first sanitize it and remove the tags:
sanitize(best_practice.milestone.description, :tags=>[])
I then shows ok, the
is removed.
But if I decide to truncate the text like this:
sanitize(best_practice.milestone.description, :tags=>[]).truncate(30)
The
is visible again on my web page. All the special chars will actually be visible.
What can I do to avoid truncate to make this special chars visible?
Dealing with sanitize helpers and truncation can be tricky. There are a lot of different sanitize helpers: h, CGI::escapeHTML, sanitize, strip_tags, html_safe, etc. Sanitization and truncation do not work well together if a string is truncated between an opening and a closing tag or right in the middle of a special HTML character.
The following statement seems to work
sanitize(text, :tags=>[]).truncate(30, :separator => " ").html_safe
The trick is to a pass a :separator option to truncate text at a natural break.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With