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)

Collapse
 
raajaryan profile image
Deepak Kumar

Hello everyone,

I hope you're all doing well. I recently launched an open-source project called the Ultimate JavaScript Project, and I'd love your support. Please check it out and give it a star on GitHub: Ultimate JavaScript Project. Your support would mean a lot to me and greatly help in the project's growth.

Thank you!