扩展Laravel Blade时如何将变量传递给指令?

问题描述 投票:0回答:1

创建自定义Laravel Blade指令时,如何传递变量?目前,尚未解析传递给@svg()指令的变量,并将其视为字符串:

刀片视图:

@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

        });

更新的代码(基于安德烈·达斯卡鲁的答案):

刀片模板:

 @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;
});
php laravel laravel-5 laravel-blade
1个回答
1
投票

我相信您正在寻找传递多个参数的方法,应该像这样:

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

这样,您可以调用@mydirective($ param1,$ param2,$ param3),闭包将处理将参数与单个$ arguments字符串分开的操作。

© www.soinside.com 2019 - 2024. All rights reserved.