Reputation: 1655
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;
});
Upvotes: 1
Views: 1694
Reputation: 1177
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.
Upvotes: 2