How to trim the Node field is rendered in page.html.twig? I have rendered the node(custom) field in page.html.twig. Custom field is a summary text field.

And now, I want to trim the text field.

I have tried the below code,

{% set summary = node.field_custom|render|striptags %}
{{ summary|length &gt; 10 ? summary|slice(0, 10) ~ '...' : summary }}


This is not working in page.html.twig. But its working only in the node.html.twig.

Showing error like,

Uncaught PHP Exception Exception: "Object of type Drupal\\Core\\Field\\FieldItemList cannot be printed."


How do I trim the summary field which is rendered in page.html.twig.

Please help me to solve this ?

NOTE: I could not control it in the managed Display section. If the reduce the number in the Trim character section, its not working.
We had a similar issue on our site recently. You are trying to print a FieldItemList, which has no __toString function, and therefore cannot be implicitly converted to a string, as you are trying to do.

In your case, node.field_custom appears to be a FieldItemList. I know, you thought it was just a string value from a field -- but it's not. Drupal treats ALL fields as FieldItemLists in the API, even in cases where the field can't possibly contain more than one value. (This presumably makes the implementation cleaner.)



One quick solution to your problem, although this is a bit messy, is to call first(), to get a TypedDataInterface, getValue(), which returns an associative array, and ['value'], in your Twig template, like so:

node.field_custom.first().getValue()['value']


That should return a string. However, for those functions to be accessible in a Twig template, you need to enable them in settings.php and clear the system cache. Here's what worked for us:

$settings['twig_sandbox_whitelisted_methods'] = [
        'first',
        '__toString',
        'bundle',
        'id',
        'label',
];


But in your case, you may have to whitelist more methods to get what you want.

Here is some more information on discovering variables in Twig templates.