I want to display first 100 characters from a rich text field.

I tried this:

{% set sumtext =  entry.bodyContent.type('text').first().text|hacksaw(chars='100', append='...') %}

But if there was a new paragraph in the first 100 characters and no full stop - both paragraphs are just joined together without a space.

I then tried:

{% set sumtext =  entry.bodyContent.type('text').first().text|hacksaw(allow='<p>', chars='100', append='...') %}

But the

gets displayed on the screen instead of the new line.

what is my best method to display the first 100 characters from a rich text field?


In my opinion, the first thing you should do is remove all HTML tags. It's not just paragraph tags which could cause you problems... what about <strong>, <a> or <img> tags which get cut off?

For legibility sake, let's also break this down into multiple steps:

{% set textBlock = entry.bodyContent.type('text').first() %}
{% set plainText = textBlock.text|striptags %}
{% set sumtext   = plainText|hacksaw(chars='100', append='...') %}

And finally, if you do want your text wrapped in a paragraph tag, just reapply that when you output it:

<p>{{ sumtext }}</p>

Since you mentioned having an issue with two paragraphs getting mushed together, let me address that too... You'll want to make use of the Craft replace filter, which can handle regex.

Couple of ways you could tackle that:

  • {% set plainText = plainText|replace('/\. */', '. ') %} (ensures periods are followed by a single space)
  • {% set textBlock = textBlock|replace('/<\/p> *<p>/', ' ') %} (gracefully combines paragraphs with a space in between)
  • Craft's replace filter is masked by Twig's replace filter, and the net result is no regex: bug report May 12 '15 at 1:55
  • Ok - so while this bug exists I won't be able to use the 2 reg ex replace options you displayed above?
    – mmc501
    May 12 '15 at 9:31
  • http://craftcms.stackexchange.com/a/9517/130 has some options May 12 '15 at 16:06
  • You can also check out the Low Regex filter... It's no longer supported, since Craft (normally) has this rolled into the core. But since the core version currently has a bug, you can probably still use Low Regex instead.
    – Lindsey D
    May 12 '15 at 17:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.