简体   繁体   中英

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) {

        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 template:

 @php($svg = 'test.svg')
 @svg($svg, 'fill-white')

AppServiceProvider:

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

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

I believe you are looking for ways to pass multiple parameters, which should go like this:

eval("\$params = [$arguments];");
list($param1, $param2, $param3) = $params;

That way you can call @mydirective($param1, $param2, $param3) and the closure will handle breaking the params apart from the single $arguments strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM