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
use App\Service\UxPackageRepository;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[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>
Symfony logo

UX Twig Components

<twig:Alert message="I am a success alert!" />
<twig:Alert
    type="danger"
    message="Oh no! The dinos escaped!"
/>

Install It

$ composer require symfony/ux-twig-component