2016-12-06 43 views
2

我正在尝试创建刀片指令以突出显示某些将从我的搜索查询返回的单词。将多个参数传递给刀片指令

这是我的刀片指令:

class AppServiceProvider extends ServiceProvider 

{ 
    public function boot() 
    { 
     Blade::directive('highlight', function($expression, $string){ 

      $expressionValues = preg_split('/\s+/', $expression); 

      foreach ($expressionValues as $value) { 
       $string = str_replace($value, "<b>".$value."</b>", $string); 
      } 

      return "<?php echo {$string}; ?>"; 
     }); 
    } 

    public function register() 
    { 
    } 
} 

我在刀片这样调用:

@highlight('ho', 'house') 

但是,这个误差修改是继我:

Missing argument 2 for App\Providers\AppServiceProvider::App\Providers\{closure}() 

如何解决它?

回答

0

我认为你只能传递一个参数。它不漂亮,但你可以通过你的参数,这样一个数组:

@highlight(['expression' => 'ho', 'string' => 'house']) 

所以,你的指令可能是

class AppServiceProvider extends ServiceProvider 

{ 
    public function boot() 
    { 
     Blade::directive('highlight', function($array){ 

      $expressionValues = preg_split('/\s+/', $array['expression']); 

      foreach ($expressionValues as $value) { 
       $array['string'] = str_replace($value, "<b>".$value."</b>", $array['string']); 
      } 

      return "<?php echo {$array['string']}; ?>"; 
     }); 
    } 

    public function register() 
    { 
    } 
} 

在这里找到:https://laracasts.com/discuss/channels/laravel/how-to-do-this-blade-directive

+0

错误:'非法串抵消“表达” –

0
Blade::directive('highlight', function($arguments){ 

     list($arg1, $arg2) = explode(',',str_replace(['(',')',' ', "'"], '', $arguments)); 

     $expressionValues = preg_split('/\s+/', $arg1); 

     $output = ""; 

     foreach ($expressionValues as $value) { 
      $output .= str_replace($value, "<b>".$value."</b>", $arg2); 
     } 

     return "<?php echo \"{$output}\"; ?>"; 
    });