marcgoertz/shorten-twig
最新稳定版本:1.0.0
Composer 安装命令:
composer require marcgoertz/shorten-twig
包简介
A Twig extension for the marcgoertz/shorten package.
README 文档
README
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.
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$lengthby 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/shortenv5.0+
Requirements
- PHP 8.2+
- Twig 3.0+
marcgoertz/shorten5.0+
Development
Running Tests
composer test
Code Style
composer lint composer fix
License
MIT © Marc Görtz
统计信息
- 总下载量: 19
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-08-19