marcgoertz/shorten-twig

A Twig extension for the marcgoertz/shorten package.

1.0.0 2025-08-19 13:11 UTC

This package is auto-updated.

Last update: 2025-08-19 13:27:06 UTC


README

A Twig extension for the marcgoertz/shorten package that safely truncates HTML markup while preserving tags, handling entities, and supporting Unicode/emoji with optional word-safe truncation.

Test Coverage Status Packagist PHP Version Support Packagist Downloads Packagist Stars MIT License

Installation

I recommend using Composer for installing and using the Shorten Twig Extension:

composer require marcgoertz/shorten-twig

Usage

Basic Setup

<?php
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Marcgoertz\Shorten\ShortenTwigExtension;

$loader = new FilesystemLoader('templates');
$twig = new Environment($loader);
$twig->addExtension(new ShortenTwigExtension());
?>

Template Usage

{{ '<a href="https://example.com/">Go to example site</a>'|shorten(10) }}

Output:

<a href="https://example.com/">Go to exam</a>

Filters

shorten

Safely truncate text or HTML markup using the marcgoertz/shorten library.

shorten(length = 100, suffix = '…', appendixInside = false, wordsafe = false, delimiter = ' ')

Parameters

  • 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 $length by 1 (default: false)
  • bool $wordsafe: Wordsafe truncation, cuts at word boundaries (default: false)
  • string $delimiter: Delimiter for wordsafe truncation (default: ' ')

Examples

{# 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>… #}

Features

  • ✅ 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/shorten v5.0+

Requirements

Development

Running Tests

composer test

Code Style

composer lint
composer fix

License

MIT © Marc Görtz