-
-
Notifications
You must be signed in to change notification settings - Fork 0
Twig Adapter
InitPHP\Views\Adapters\TwigAdapter renders
Symfony Twig templates.
composer require twig/twigtwig/twig ^3.0 is supported.
public function __construct(string $viewDir, string $cacheDir)-
$viewDir— the directory holding the Twig templates. -
$cacheDir— a writable directory for compiled templates.
Both directories must exist, or a ViewInvalidArgumentException is
thrown.
use InitPHP\Views\Facade\View;
use InitPHP\Views\Adapters\TwigAdapter;
View::via(new TwigAdapter(__DIR__ . '/views', __DIR__ . '/cache'));Twig does not add a file extension — include it in the view name exactly as the file is named:
echo view('dashboard.html.twig', ['username' => 'admin']);views/dashboard.html.twig:
<h1>Welcome, {{ username }}</h1>Render several templates in order:
echo view(['header.twig', 'content.twig', 'footer.twig'], ['title' => 'Home']);Twig auto-escapes output according to its configuration, which is a key difference from the Pure PHP adapter.
Use getEnvironment() to reach the underlying Twig\Environment and add
globals, filters, functions or extensions:
public function getEnvironment(): \Twig\Environmentuse Twig\TwigFilter;
$twig = new TwigAdapter(__DIR__ . '/views', __DIR__ . '/cache');
$environment = $twig->getEnvironment();
$environment->addGlobal('app_name', 'InitPHP');
$environment->addFilter(new TwigFilter('shout', static fn (string $v): string => strtoupper($v)));
View::via($twig);{{ app_name }} — {{ 'hello'|shout }} {# InitPHP — HELLO #}The cache directory you pass is handed straight to Twig as its cache option,
so compiled templates are written there. Make sure it is writable by the web
server user. To iterate on templates during development, you can enable Twig's
auto-reload through the environment:
$twig->getEnvironment()->enableAutoReload();- Twig documentation (official)
- Recipes
- API Reference
initphp/views · MIT License · part of the InitPHP family
Source · Issues · Discussions · Packagist · Contributing · Security Policy
Getting Started
Adapters
Reference
Guides
Other