Drupal - How to trim body text (field_body)?

There's a few solutions you can try but take note truncating strings with html is generally a bad idea due to having potential unclosed or malformed tags.

1. Use |raw to output the html as html, may produce malformed tags:

{% set text = content.field_body|render %}
{{ text|length > 200 ? text|slice(0, 200)|raw ~ '...' : text|raw }}

2. Strip html first, cleaner:

{% set text = content.field_body|render|striptags %}
{{ text|length > 200 ? text|slice(0, 200) ~ '...' : text }}

3. Register a twig extension (untested):

https://gist.github.com/leon/2857883

Another helpful extension you can check out is the Text extension, which helps you prevent chopping up words:

http://twig.sensiolabs.org/doc/extensions/text.html


You can now do this with the twig_extender module and use |truncate.

Here is an example of how to use it in the .twig template, note that I'm also using twig_field_value:

{{ content.field_name|field_value|first['#text']|truncate(15, true, '....') }}

note: I usually keep my devel settings (./admin/config/development/devel) set to use Symfony var-dumper and can figure out the chain with

ie: {{ devel_dump(content.field_name|field_value) }}


Improvements:

  1. if you strip tags you should |trim to get rid of whitespace
  2. trim on word boundary - see below slice() and split()
  3. Use ellipsis (…) rather than "..."
  4. |raw the output

{% set text = content.field_header_intro|render|striptags|trim %}

{{ (text|length > 200 ? text|slice(0, 201)|split(' ')|slice(0, -1)|join(' ') ~ '&hellip;' : text)|raw }}</code>

Tags:

Theming

8