The framework provides deep integration with the Twig Template engine including access to IoC scopes, i18n integration, and caching.
To install Twig bridge component, run the following command:
composer require spiral/twig-bridge
Activate the component by adding Spiral\Twig\Bootloader\TwigBootloader
bootloader to your Kernel
:
public function defineBootloaders(): array
{
return [
// ...
\Spiral\Views\Bootloader\ViewsBootloader::class,
\Spiral\Bootloader\Views\TranslatedCacheBootloader::class, // keep localized views in separate cache files
\Spiral\Twig\Bootloader\TwigBootloader::class,
// ...
];
}
Read more about bootloaders in the Framework — Bootloaders section.
You can add any custom extension to Twig via the addExtension
method of TwigBootloader
:
class TwigExtensionBootloader extends Bootloader
{
public function boot(TwigBootloader $twig): void
{
$twig->addExtension(MyExtension::class);
// custom options
$twig->setOption('name', 'value');
}
}
You can use twig views immediately. Create a view with .twig
extension in the app/views
directory.
Hello, {{ name }}!
You can use this view without an extension in your controllers:
public function index(): string
{
return $this->views->render('filename', ['name' => 'User']);
}
Note
You can freely use twig'sinclude
andextends
directives.
To access the value from the IoC scope:
Hello, {{ name }}!
{{ get("Spiral\\Http\\Request\\InputManager").attribute('csrfToken') }}
In Twig you can use the dump
function to display information about a variable, including its type and value. It's
useful for debugging purposes in your templates.
To enable the function create a new Bootloader: TwigDebugBootloader
:
namespace App\Application\Bootloader;
use Spiral\Boot\Bootloader\Bootloader;
use Spiral\Twig\Bootloader\TwigBootloader;
use Twig\Extension\DebugExtension;
final class TwigDebugBootloader extends Bootloader
{
public function boot(TwigBootloader $twig)
{
$twig->addExtension(new DebugExtension());
$twig->setOption('debug', true);
}
}
Activate the component by adding TwigDebugBootloader
bootloader to your Kernel
:
public function defineBootloaders(): array
{
return [
// ...
\App\Application\Bootloader\TwigDebugBootloader::class,
// ...
];
}
Read more about bootloaders in the Framework — Bootloaders section.
Afterwards you can use the {{ dump() }}
function in your template.
<pre>
{{ dump(cats) }}
</pr>
cats
in this case is the variable we would like to debug.
You can assign more variables by passing them as arguments:
{{ dump(cats, dogs, birds) }}
If we don't pass any value to the function, all variables from the current context will be dumped.
See more
For more information, visit the official twig documentation.