Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ux Twig Component Laravel Package

codeblick/ux-twig-component

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require symfony/ux-twig-component
    

    Ensure your project uses Symfony 6.3+ or Symfony 7.x (check requirements).

  2. Enable the Bundle: Add to config/bundles.php:

    return [
        // ...
        Symfony\UX\TwigComponent\TwigComponentBundle::class => ['all' => true],
    ];
    
  3. First Use Case: Render a basic alert component in a Twig template:

    {{ include_ux_twig_component('alert', {
        type: 'success',
        title: 'Success!',
        text: 'Your action was completed.'
    }) }}
    

    Verify the output matches the alert example.


Implementation Patterns

Core Workflow

  1. Component Registration: Extend existing components or create custom ones via TwigComponentExtension:

    // src/Twig/AppExtension.php
    use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;
    
    #[AsTwigComponent('my_component')]
    public function myComponent(array $data): string
    {
        return $this->renderView('components/my_component.html.twig', $data);
    }
    
  2. Template Integration: Use include_ux_twig_component in Twig:

    {# Pass dynamic data #}
    {{ include_ux_twig_component('my_component', {
        title: 'Dynamic Title',
        items: ['Item 1', 'Item 2']
    }) }}
    
  3. Data Binding: Bind objects to components for cleaner templates:

    // Controller
    return $this->render('page.html.twig', [
        'userAlert' => new UserAlert($user),
    ]);
    
    {# Template #}
    {{ include_ux_twig_component('alert', userAlert) }}
    

Advanced Patterns

  • Component Inheritance: Extend base components (e.g., alert) to add functionality:

    #[AsTwigComponent('custom_alert')]
    public function customAlert(array $data): string
    {
        $data['extra'] = 'Custom logic here';
        return $this->renderView('components/custom_alert.html.twig', $data);
    }
    
  • Reusable Blocks: Use Twig’s {% block %} within components for modularity:

    {# components/base_card.html.twig #}
    <div class="card">
        {% block content %}{% endblock %}
    </div>
    
  • Event-Driven Components: Trigger events in components (e.g., for Turbo interactions):

    {{ include_ux_twig_component('modal', {
        onClose: 'turbo:click->#modal-close'
    }) }}
    

Gotchas and Tips

Common Pitfalls

  1. Component Naming Conflicts: Ensure custom component names (e.g., my_component) don’t clash with Symfony’s built-in components. Prefix with your bundle name (e.g., app_my_component).

  2. Circular Dependencies: Avoid circular references between components and their templates. Use renderView sparingly to prevent infinite loops.

  3. Data Type Mismatches: Components expect specific data structures. Validate inputs:

    #[AsTwigComponent('user_card')]
    public function userCard(array $data): string
    {
        if (!isset($data['user'])) {
            throw new \InvalidArgumentException('User data required.');
        }
        // ...
    }
    

Debugging Tips

  • Check Registered Components: Dump available components in Twig:

    {{ dump(_twig_ux_components) }}
    
  • Template Paths: Ensure component templates (e.g., components/alert.html.twig) are in your Twig loader paths. Use debug:config twig to verify.

  • Event Listeners: Debug Turbo/Stimulus events by inspecting the browser’s Network tab for Mercure updates or Turbo streams.

Extension Points

  1. Custom Attributes: Add attributes to components for metadata or validation:

    #[AsTwigComponent('validated_form')]
    #[Attribute\RequiresDataType('form')]
    public function validatedForm(array $data): string { ... }
    
  2. Dependency Injection: Inject services into components via Twig’s Environment:

    public function __construct(private Environment $twig)
    {
        $this->twig = $twig;
    }
    
  3. Testing: Test components in isolation using TwigTester:

    $twig = new \Twig\Environment($loader);
    $twig->addExtension(new TwigComponentExtension());
    $result = $twig->render('components/alert.html.twig', ['type' => 'error']);
    $this->assertStringContainsString('Error', $result);
    

Performance

  • Cache Components: Enable Twig’s cache for components:
    # config/packages/twig.yaml
    twig:
        cache: '%kernel.cache_dir%/twig'
    
  • Avoid Over-Fetching: Pass only necessary data to components to reduce template complexity.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
andydefer/laravel-cluster
aimeos/ai-admin-mcp
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor