danmartuszewski/ux-twig-component
Install the Package
composer require danmartuszewski/ux-twig-component
Ensure your Laravel project uses Symfony’s Twig bridge (if not, install via composer require symfony/twig-bundle).
Register the Twig Component Bundle
Add to config/app.php under providers:
Symfony\UX\TwigComponent\TwigComponentBundle::class,
Create Your First Component
Generate a component class (e.g., AlertComponent) in app/Components/:
namespace App\Components;
use Symfony\UX\TwigComponent\AbstractComponent;
class AlertComponent extends AbstractComponent {
public string $type = 'success';
public string $message;
public static function getComponentName(): string { return 'alert'; }
public static function getTemplate(): ?string { return '@App/components/alert.html.twig'; }
}
Define the Twig Template
Create resources/views/components/alert.html.twig:
<div class="alert alert-{{ this.type }}">
{{ this.message }}
</div>
Use the Component in Twig
In any Twig template (e.g., resources/views/home.blade.php):
{{ component('alert', { message: 'Hello Twig Components!' }) }}
Reusable UI Units
CardComponent with dynamic title/body/slot support.Data Binding
$user = User::find(1);
return view('profile', ['user' => $user]);
{{ component('user-card', { user: user }) }}
Slot-Based Layouts
Extend AbstractComponent to support slots (like Vue/React):
public function getSlots(): array { return ['header', 'footer']; }
{{ component('card') }}
{% slot('header') %}Title{% endslot %}
Content
{{ endcomponent('card') }}
Integration with Live Components
Combine with symfony/ux-live-component for interactivity:
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
#[AsLiveComponent]
class InteractiveAlert extends AlertComponent { ... }
resources/views/components/ for clarity.@App/components/ namespace conventions.Template Paths
getTemplate() returns a valid Twig path (e.g., @App/components/alert.html.twig).resources/views/components/ and prefix with @App/.Caching Issues
php artisan view:clear
Experimental Status
Slot Scope
{{ component('child', { slotData: slot('header') }) }}
php artisan twig:debug
dd($this) in the component class to inspect bound data.Custom Component Traits Extend functionality via traits (e.g., for form handling):
trait FormComponentTrait {
public function getForm(): FormInterface { ... }
}
Dynamic Templates
Override getTemplate() to fetch templates dynamically:
public static function getTemplate(): string {
return '@App/components/' . self::getComponentName() . '.html.twig';
}
Live Component Events Use Symfony UX’s event system for real-time updates:
use Symfony\UX\LiveComponent\DefaultActionTrait;
class LiveAlert extends AlertComponent {
use DefaultActionTrait;
public function dismiss(): void { ... }
}
How can I help you explore Laravel packages today?