Object-Oriented Templates
PHP Classes that render: Twig Components
Create reusable, object-oriented templates. PHP class + template = Twig components.
composer require symfony/ux-twig-component
// ... use statements hidden - click to show
#[AsTwigComponent]
class Alert
{
public string $type = 'success';
public string $message;
public function __construct(private UxPackageRepository $packageRepository)
{
}
public function getIcon(): string
{
return match ($this->type) {
'success' => 'circle-check',
'danger' => 'circle-exclamation',
};
}
public function getPackageCount(): int
{
return $this->packageRepository->count();
}
}
<div class="alert alert-{{ type }} alert-dismissible" role="alert">
<twig:Icon name="{{ this.icon }}" class="me-2" />
{{ message }}
{% if type == 'success' %}
<a href="{{ path('app_packages') }}" class="alert-right-message">
(browse all {{ this.packageCount }} packages)
</a>
{% endif %}
</div>
UX Twig Components
I am a success alert!
<twig:Alert message="I am a success alert!" />
Oh no! The dinos escaped!
<twig:Alert
type="danger"
message="Oh no! The dinos escaped!"
/>
Install It
$ composer require symfony/ux-twig-component