Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails truncate method adds special characters

I have this html text:

<p> I'm a html &nbsp; 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 &nbsp; is removed.

But if I decide to truncate the text like this:

sanitize(best_practice.milestone.description, :tags=>[]).truncate(30)

The &nbsp; 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?

like image 933
ndemoreau Avatar asked Dec 21 '22 16:12

ndemoreau


1 Answers

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.

like image 82
0x4a6f4672 Avatar answered Jan 10 '23 02:01

0x4a6f4672