Skip to content

Twig

This page covers extending Twig with custom functions and filters, and links out to useful references.

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:

app/Hook/TimberHook.php
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>

Check the links above before adding a filter — it may already exist.

Open app/Hook/TimberHook.php and add your filter inside registerFilters:

app/Hook/TimberHook.php
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>