reun / twig-utilities
Various Twig utilities and extensions
Requires
- php: ^8.2
- twig/twig: ^3.0
Requires (Dev)
- codeception/specify: ^1.3
- ergebnis/composer-normalize: ^2.44
- ezyang/htmlpurifier: ^4.18
- friendsofphp/php-cs-fixer: ^3.64
- php-di/php-di: ^6.0
- phpstan/phpstan: ^2.0
- phpstan/phpstan-strict-rules: ^2.0
- phpunit/phpunit: ^9.1
- psr/http-message: ^2.0
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
- reun/php-app-config: ^0.2.0
- slim/slim: ^4.4
Suggests
- ezyang/htmlpurifier: Required by HtmlPurify filter
- psr/http-message: Required for Slim utilities
- psr/http-server-handler: Required for Slim utilities
- psr/http-server-middleware: Required for Slim utilities
- slim/slim: Slim Framework ^4.0 is required for Slim specific features
README
Various utility filters, functions and Slim integration for Twig.
Installation
Install package using Composer
composer require reun/twig-utilities
Usage - Filters and functions
Functions and filters are defined in separate classes and provide either
getFilter()
or getFunction()
static method that can be used to add them to
Twig. The class name beginning with a lowercase character becomes the name of
the filter/function in Twig. E.g. CopyrightYear
becomes copyrightYear()
.
The recommended way is to create a new Twig extension for your project and add
filters and functions in getFilters()
and getFunctions()
.
use Reun\TwigUtilities\Filters\Htmlpurify; use Reun\TwigUtilities\Functions\CopyrightYear; use Twig\Extension\AbstractExtension; class MyExtension extends AbstractExtension { public function getFilters(): array { return [ Htmlpurify::getFilter(), ]; } public function getFunctions(): array { return [ CopyrightYear::getFunction(), ] } } // Add extension to Twig. $twig->addExtension(new MyExtension());
Some filters and functions have external dependencies. To use them you must add a runtime loader to Twig environment.
use DI\Container; use Twig\RuntimeLoader\ContainerRuntimeLoader; $twig->addRuntimeLoader(new ContainerRuntimeLoader(new Container()));
Creating new filters and functions
Just extend either Reun\TwigUtilities\Filters\AbstractFilter
or
Reun\TwigUtilities\Functions\AbstractFunction
and implement __invoke()
.
Options can be specified by overriding getOptions()
method.
Available features
Filters
Functions
Slim utilities
FAQ and notes
Where is the Markdown filter?
Use Twig's own
markdown_to_html
filter.
Handling dates and timezones
It is recommended to handle all dates and times as UTC
and use that as the PHP
timezone setting. Twig's builtin
date
filter should be
used to output dates in a different timezone and can be combined with
formatDateRange()
etc. See Twig's documentation on how to set the
timezone.
Example of formatting event times in different timezone:
<div> {{ formatDateRange(event.startDate|date, event.endDate|date) }} </div>
Development
Run composer dev
to start a test server. The code is located in
tests/functional/TwigUtilities
.