如何扩展Laravel Blade功能并添加"中断"和"继续"支持

Fra*_*ste 6 php laravel blade laravel-4 laravel-routing

我想为我的Blade引擎添加@continue@break声明以控制我的循环.

我已经看到extend了BladeEngine的一个函数来源,我试图在我的routes.php文件中使用它:

Blade::extend(function ($value) {
    $pattern = Blade::createMatcher('continue');
    return preg_replace($pattern, '$1<?php continue; ?>$2', $value);
});
Run Code Online (Sandbox Code Playgroud)

我的一个观点是:

@if (isset($meta['foo']) && !$meta['bar'])
    @continue
@else
    <li>{{$meta['pseudo']}}</li>
@endif
Run Code Online (Sandbox Code Playgroud)

但渲染的HTML页面显示了我@continue.

知道如何使它工作?

Gad*_*oma 8

在将提供的代码片段添加到后,您是否清除了缓存/编译的视图文件routes.php?如果没有,请尝试这样做,因为只有在检测到更改时,Blade才会重新编译视图.因此,如果在添加代码后没有清除已编译的视图,则渲染的html中没有任何更改.

如果不是这样,请尝试使用普通的旧正则表达式而不是Blade :: createMatcher,这个漂亮的定义将为您提供oneliner中的continue和break支持.

Blade::extend(function($value)
{
  return preg_replace('/(\s*)@(break|continue)(\s*)/', '$1<?php $2; ?>$3', $value);
});
Run Code Online (Sandbox Code Playgroud)

它应该工作,即使放在routes.php中,虽然最好将它放在一个单独的文件中(例如blade.php并将其包含在global.php中).无论如何,它必须在处理视图之前加载.