reun/twig-utilities

Various Twig utilities and extensions

0.12.0 2024-11-21 17:23 UTC

This package is auto-updated.

Last update: 2024-11-21 17:30:28 UTC


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.