Frage

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?

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top