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— directory holding the Twig templates.$cacheDir— 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']);Use getEnvironment() to reach the underlying Twig\Environment and add
globals, filters, functions or extensions:
$twig = new TwigAdapter(__DIR__ . '/views', __DIR__ . '/cache');
$environment = $twig->getEnvironment();
$environment->addGlobal('app_name', 'InitPHP');
$environment->addFilter(new \Twig\TwigFilter('shout', static fn (string $v): string => strtoupper($v)));
View::via($twig);{{ app_name }} — {{ 'hello'|shout }}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.