A simple script that allows a snippet of HTML to be truncated while preserving its structure. The text is truncated based on the number of visible characters in the string, ignoring the size of any markup tags.

Requirements

The truncator requires Nokogiri to parse out the HTML string.

Using with Jekyll

If you’re using Jekyll, add the html_filters.rb file to your _plugins directory - this will give you the helper truncatehtml as a Liquid filter. In your views, you can use this function in the same way as you would use the normal truncate filter:

page.content | truncatehtml: 500