面向对象的模板

渲染的 PHP 类:Twig 组件

创建可重用、面向对象的模板。PHP 类 + 模板 = Twig 组件。

composer require symfony/ux-twig-component
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent]
class Alert
{
    public string $type = 'success';
    public string $message;

    public function getIcon(): string
    {
        return match ($this->type) {
            'success' => 'bi:check-circle',
            'danger' => 'bi:exclamation-circle',
        };
    }
}
<div class="alert alert-{{ type }} alert-dismissible" role="alert">
    <twig:ux:icon name="{{ this.icon }}" class="Icon bi" />
    {{ message }}
</div>
Symfony logo

UX Twig 组件

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

安装它

$ composer require symfony/ux-twig-component