This project provides several Twig extensions for internal projects.
The preferred method of installation is via Composer. Run the following command to install the package and add it as a requirement to your project's composer.json
:
composer require gubler/twig-extensions
$twig = new Twig_Environment($loader, $options);
$twig->addExtension(new Gubler\Twig\Extension\FileIconClassExtension());
$twig->addExtension(new Gubler\Twig\Extension\FlashMessagesExtension());
$twig->addExtension(new Gubler\Twig\Extension\InstanceOfExtension());
$twig->addExtension(new Gubler\Twig\Extension\TableSortIconExtension());
For Symfony, register it in your services.yaml
services:
gubler.twig_extension.file_icon_class:
class: Gubler\Twig\Extension\FileIconClassExtension
tags: [twig.extension]
gubler.twig_extension.flash_messages:
class: Gubler\Twig\Extension\FlashMessagesExtension
tags: [twig.extension]
gubler.twig_extension.instance_of:
class: Gubler\Twig\Extension\InstanceOfExtension
tags: [twig.extension]
gubler.twig_extension.table_sort_icon:
class: Gubler\Twig\Extension\TableSortIconExtension
tags: [twig.extension]
You can also use the MimeTypeToIconClass
library directly and inject it into your classes by registering it as a service:
services:
Gubler\Twig\Extension\Lib\MimeTypeToIconClass: ~
This maps a mimetype to a FontAwesome file icon. This currently only supports the following filetypes:
- MS Word
- MS Excel
- MS PowerPoint
All other files return a generic file icon.
{{ 'application/vnd.ms-excel'|fileIconClass }}
This extension will iterate through the flashes of a given Session and convert them to Bootstrap 5 alerts.
This looks for the flash keys of success
, warning
, error
, and notice
.
Creating the flashes:
# In a Symfony controller:
$this->addFlash('success', 'This is a SUCCESS message');
$this->addFlash('error', 'This is an ERROR message');
$this->addFlash('warning', 'This is a WARNING message');
$this->addFlash('notice', 'This is a NOTICE message');
Rendering all flashes:
{{ flashMessages(app.session) }}
This extension provides PHP's instanceof
type operator as a Twig test.
{# date is \DateTime object #}
{{ date is instanceof("\\DateTime") ? 'ok' : 'bad' }}
This filter allows you to pass the column name, the sorted column name, and sort direction and get back a FontAwesome sorting icon classes.
<i class="{{ tableSortIcon('col1', 'col1', 'asc') }}"></i>
Contributions are welcome! Please read CONTRIBUTING for details.
This project adheres to a Contributor Code of Conduct. By participating in this project and its community, you are expected to uphold this code.
The gubler/twig-extensions library is copyright © Daryl Gubler and licensed for use under the MIT License (MIT). Please see LICENSE for more information.