Back to list

Twig - Template Engine

Lv.51313@mukitaro21 playsDec 31, 2025

Twig template engine setup with custom filters and functions.

preview.php
PHP
1use Twig\Environment;
2use Twig\Loader\FilesystemLoader;
3use Twig\Extension\AbstractExtension;
4use Twig\TwigFilter;
5use Twig\TwigFunction;
6
7class TwigSetup
8{
9 public function createEnvironment(string $templatePath): Environment
10 {
11 $loader = new FilesystemLoader($templatePath);
12 $twig = new Environment($loader, [
13 'cache' => '/tmp/twig_cache',
14 'auto_reload' => true,
15 'strict_variables' => true
16 ]);
17
18 $twig->addExtension(new CustomExtension());
19 return $twig;
20 }
21}
22
23class CustomExtension extends AbstractExtension
24{
25 public function getFilters(): array
26 {
27 return [
28 new TwigFilter('price', [$this, 'formatPrice']),
29 new TwigFilter('truncate', [$this, 'truncateText'])
30 ];
31 }
32
33 public function getFunctions(): array
34 {
35 return [
36 new TwigFunction('asset_url', [$this, 'getAssetUrl'])
37 ];
38 }
39
40 public function formatPrice(float $value): string
41 {
42 return '$' . number_format($value, 2);
43 }
44
45 public function truncateText(string $text, int $length): string
46 {
47 return mb_substr($text, 0, $length) . '...';
48 }
49
50 public function getAssetUrl(string $path): string
51 {
52 return '/assets/' . ltrim($path, '/');
53 }
54}

Custom problems are not included in rankings