How to trim body text (field_body)? I've created a view for a node which shows the content as rendered entity. Among others, I output the body field in the twig template:

{{ content.field_body }}


Now, I'd like to limit the text to 200 characters and put three dots. I've tested three different ways to do that, but nothing has worked. The problem is, that each way counts and trims the HTML characters too.

1: I've added the format "Trimmed" in "Manage display" => The text is limited but not correct. And I do not have the three dots.

2: I've trimmed the text in the twig template. But to count the text I have to render it first. Thereby, twig outputs the text as HTML (I see HTML tags on my page!)

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


3: I've tried to solve the problem in template_preprocess_node(). Here I have the same problem with counting the HTML markup too.

$body_text = $node-&gt;get('field_body')-&gt;getValue()[0]['value'];
$trimmed_text = substr($body_text, 0, 200) . '...';


How can I trim my text right?

Thank you very much for your help!
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 &gt; 200 ? text|slice(0, 200)|raw ~ '...' : text|raw }}


2. Strip html first, cleaner:

{% set text = content.field_body|render|striptags %}
{{ text|length &gt; 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