Change record status: 
Project: 
Introduced in branch: 
main
Introduced in version: 
12.x
Description: 

Summary

The text_trimmed and text_summary_or_trimmed field formatters have a new "Exclude HTML tags from trim length" setting. When enabled, the trim length is measured against the visible text only, so markup such as long link URLs or nested inline tags no longer consumes the character limit.

  • The setting defaults to enabled for newly configured fields.
  • Existing displays are set to disabled by text_post_update_add_exclude_html_tags_setting(), so upgraded sites keep their current behavior. NOTE: Sites reinstalled from previously exported configuration do
    not run post-updates and will pick up the new default.
  • The trimmed value is still cut at a logical break point (paragraph, line break or end of sentence) at or before the limit, so the output is often shorter than the configured length.
  • A manual <!--break--> summary delimiter still takes precedence over the setting and over the trim length.
  • When the setting is enabled, the truncated markup is repaired with \Drupal\Component\Utility\Html::normalize(), so tags left open by the cut are closed in the output.

Config schema adds an exclude_html_tags boolean to field.formatter.settings.text_trimmed and field.formatter.settings.text_summary_or_trimmed. Update any configuration written in code, recipes or exported YAML accordingly.

For module developers, the formatter passes the setting to its pre-render callback through a new #exclude_html_tags render array property, and TextTrimmedFormatter::truncateHtml() is available to cut an HTML string at a given number of visible characters.

Before

With a trim length of 100 and this field value:

<p><a href="https://example.com/some/long/path"><em><span><strong>The maximum number of characters used in the trimmed version of a post. Drupal will use this setting to determine at which offset long posts should be
  trimmed.</strong></span></em></a></p>

the opening tags consumed most of the limit, leaving 44 visible characters:

The maximum number of characters used in the

After

With "Exclude HTML tags from trim length" enabled, only the visible text counts, and the value is cut at the sentence boundary before the 100 character limit:

The maximum number of characters used in the trimmed version of a post.

Impacts: 
Site builders, administrators, editors
Module developers