mercredi 19 février 2020

How can I pass a variable to a directive when extending Laravel Blade?

When creating a custom Laravel Blade directive how can I pass a variable in? At the moment the variable passed to the @svg() directive is not parsed and is treated as a string:

Blade view:

@svg($svg->url, 'fill-white')

AppServiceProvider.php

    Blade::directive('svg', function ($arguments) {

        // Funky madness to accept multiple arguments into the directive
        list($path, $class) = array_pad(explode(',', trim($arguments, "() ")), 2, '');
        $path = trim($path, "' ");
        $class = trim($class, "' ");


            dd($path); // Outputs $svg->url

           // Required output = path/to/filename.svg

        });

UPDATED CODE (Based on Andrei Dascalu's answer):

       Blade::directive('svg', function ($arguments) {
            eval("\$params = [$arguments];");
           // Produces 'undefined variable $svg' error

            list($path, $class) = $params;
});


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire