5

I have a rich text output section I want to limit to specific number of characters or words. So user able preview the blog post and link to the full blog. I try entry.body|slice(0, 100) ~ '...'. But it slice of my html tag and display html code in front end.

Hs Tung
  • 367
  • 2
  • 12

4 Answers4

18

No need for a plugin, just use twig's slice filter, combined with the striptags filter.

I've thrown in the default filter for good measure, in case the body is empty for some reason.

{{ entry.body|striptags|slice(0,100)|default('Read more') }}...

slice will simply output the first 100 characters (starting at 0 the first character), including spaces into the template. striptags ensures that no html tags will be output.

Adam Menczykowski
  • 1,390
  • 11
  • 22
4

I found a plugin to solve this.

Which is use this plugin. https://github.com/ehousestudio/craft_hacksaw

Hs Tung
  • 367
  • 2
  • 12
2

For my future self:

This is my solution now in Craft CMS 3 and 4.

{{ 'Hello world'|truncate(10) }}
{# Output: Hello… #}

An ellipsis (…) will be appended to the string if it needs to be truncated, by default. You can customize what gets appended by passing a second argument. (Note that a longer appended string could result in more of the original string getting truncated.)

More configs available too: https://craftcms.com/docs/4.x/dev/filters.html#truncate

mateostabio
  • 526
  • 4
  • 16
2

Looks like you can extend twig with extensions. I have not tried this, but I found this extension which preserves HTML.

https://www.versioneye.com/php/dzango:twig-truncate-extension/1.0.8

I think you have to create a plugin to use it. A fast way is to follow by example on this one perhaps: https://github.com/lukeholder/craft-inflect

Ryan
  • 613
  • 1
  • 7
  • 15