A Twig extension for the
marcgoertz/shortenpackage that safely truncates HTML markup while preserving tags, handling entities, and supporting Unicode/emoji with optional word-safe truncation.
I recommend using Composer for installing and using the Shorten Twig Extension:
composer require marcgoertz/shorten-twig<?php
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Marcgoertz\Shorten\ShortenTwigExtension;
$loader = new FilesystemLoader('templates');
$twig = new Environment($loader);
$twig->addExtension(new ShortenTwigExtension());
?>{{ '<a href="https://example.com/">Go to example site</a>'|shorten(10) }}Output:
<a href="https://example.com/">Go to exam</a>…Safely truncate text or HTML markup using the marcgoertz/shorten library.
shorten(length = 100, suffix = '…', appendixInside = false, wordsafe = false, delimiter = ' ')int $length: Maximum length of truncated text (default:400)string $appendix: Text added after truncated text (default:'…')bool $appendixInside: Add appendix to last content in tags, increases$lengthby 1 (default:false)bool $wordsafe: Wordsafe truncation, cuts at word boundaries (default:false)string $delimiter: Delimiter for wordsafe truncation (default:' ')
{# Basic truncation #}
{{ 'A very long text that needs to be shortened'|shorten(20) }}
{# Output: A very long text th… #}
{# Custom suffix #}
{{ 'A very long text that needs to be shortened'|shorten(20, '...') }}
{# Output: A very long text th... #}
{# Wordsafe truncation #}
{{ 'A very long text that needs to be shortened'|shorten(20, '…', true) }}
{# Output: A very long text… #}
{# HTML markup preservation #}
{{ '<b>Bold text</b> and <i>italic text</i>'|shorten(15) }}
{# Output: <b>Bold text</b> and <i>ita</i>… #}- ✅ Preserves HTML tag structure and proper nesting
- ✅ Handles HTML entities correctly
- ✅ Supports self-closing tags (both XML and HTML5 style)
- ✅ UTF-8 and multibyte character support (including emojis)
- ✅ Wordsafe truncation to avoid cutting words in the middle
- ✅ Configurable suffix text and placement
- ✅ Easy integration with existing Twig templates
- ✅ Full compatibility with
marcgoertz/shortenv5.0+
- PHP 8.2+
- Twig 3.0+
marcgoertz/shorten5.0+
composer testcomposer lint
composer fixMIT © Marc Görtz