I needed a Rails helper like truncate but that doesn’t truncate in the middle of a tag or entity and doesn’t leave start tags without their end tags. So
and not something like
Also, I made it aware of HTML in the ellipsis text, so e.g.
only displaces four characters (for “more”) of truncated string, instead of several (for the link HTML).
Oh, and being based on Hpricot, which has a robust parser, it handles crap HTML well:
Save it as
app/helpers/text_helper.rb and make sure you’re doing
I was inspired by Mike Burns’ Truncating HTML in Ruby and Joakim Andersson’s response Rails + tidy + REXML. Joakim uses tidy to keep REXML from choking on malformed HTML. I suggested cleaning the HTML with Hpricot, and then figured it’d be fun to write my own helper using just Hpricot, not REXML.
My helper behaves just like the Rails helper in regard to what arguments it takes and how it interprets the max length – if the string is within limits, the full string is returned; if it’s longer, the truncated string including the ellipsis is limited to the max length.