DEV Community

Adam Mateusz Brożyński
Adam Mateusz Brożyński

Posted on

Laravel 11: Vite in Twig (rcrowe/TwigBridge)

This registers vite tag to Twig that allows to dynamically link css and js (works for dev and prod):

{{ vite('resources/css/app.scss')|raw }}
{{ vite('resources/css/app.js')|raw }}
Enter fullscreen mode Exit fullscreen mode

1. Create new Twig extension:

app/Twig/TwigExtension.php:

<?php
namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Twig\Markup;
use Illuminate\Foundation\Vite;

class TwigExtension extends AbstractExtension
{
    public function getFunctions(): array
    {
        return [
            new TwigFunction('vite', [$this, 'vite']),
        ];
    }

    public function vite(string $resource): string
    {
        return new Markup((new Vite)->__invoke($resource),'UTF-8');
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Generate config:

php artisan vendor:publish --provider="TwigBridge\ServiceProvider"
Enter fullscreen mode Exit fullscreen mode

3. Add extension to config:

app/config/twigbridge.php:

        'enabled' => [
            ... 
            'App\Twig\TwigExtension',
        ],
Enter fullscreen mode Exit fullscreen mode

Top comments (1)