Twig
This page covers extending Twig with custom functions and filters, and links out to useful references.
Resources
Section titled “Resources”- Twig
- Twig - Reference
- Timber - Twig
- Timber - Twig Filters
- Timber - Custom Fields
- Timber - Functions
- Timber - Text Cookbook
- Timber - Image Cookbook
Creating your own functions
Section titled “Creating your own functions”Check the links above before adding a function — it may already exist in Twig or Timber.
Open app/Hook/TimberHook.php and add your function inside registerFunctions:
public function registerFunctions(array $functions): array{ // Anonymous function $functions['hi'] = [ 'callable' => function($name = 'Mom') { echo "Hi " . $name . "!"; } ];
// Static method $functions['hi'] = [ 'callable' => Say::hi ];
return $functions;}{# Calls hi using default arguments #}<p>{{ hi() }}</p>
{# Calls hi with arguments #}<p>{{ hi('Developer') }}</p>Creating your own filters
Section titled “Creating your own filters”Check the links above before adding a filter — it may already exist.
Open app/Hook/TimberHook.php and add your filter inside registerFilters:
public function registerFilters(array $filters): array{ // Anonymous function $filters['truncate'] = [ 'callable' => function(string $text, int $length = 40) { // truncate logic return $result; } ];
// Static method $filters['truncate'] = [ 'callable' => StringUtil::truncate ];
return $filters;}{# Calls truncate using default arguments #}<p>{{ 'a super long string' | truncate }}</p>
{# Calls truncate with arguments #}<p>{{ 'a super long string' | truncate(10) }}</p>
