Object-Oriented Templates
Create reusable, object-oriented templates. PHP class + template = Twig components.
src/Twig/AlertComponent.php
use App\Service\PackageRepository;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;
#[AsTwigComponent('alert')]
class AlertComponent
{
public string $type = 'success';
public string $message;
public function __construct(private PackageRepository $packageRepository)
{
}
public function getIconClass(): string
{
return match ($this->type) {
'success' => 'fa fa-circle-check',
'danger' => 'fa fa-circle-exclamation',
};
}
public function getPackageCount(): int
{
return $this->packageRepository->count();
}
}
templates/components/alert.html.twig
<div class="alert alert-{{ type }} alert-dismissible" role="alert">
<span class="me-2 {{ this.iconClass }}"></span>
{{ message }}
{% if type == 'success' %}
<a href="{{ path('app_all_components') }}" class="alert-right-message">
(browse all {{ this.packageCount }} packages)
</a>
{% endif %}
</div>
UX Twig Components
{{ component('alert', {
message: 'I am a success alert!',
}) }}
{{ component('alert', {
type: 'danger',
message: 'Oh no! The dinos escaped!',
}) }}
$ composer require ux symfony/ux-twig-component
$ npm install --force
$ npm run watch