【PHP】如何擴充套件Laravel Blade功能並新增“中斷”和“繼續”支援
我想為我的刀片引擎新增@continue和@break語句,以便控制迴圈。
我在原始碼中看到了bladeengine的extend函式,並嘗試在routes.php檔案中使用它:
Blade::extend(function ($value) {
$pattern = Blade::createMatcher('continue');
return preg_replace($pattern, '$1<?php continue; ?>$2', $value);
});
我的觀點之一:
@if (isset($meta['foo']) && !$meta['bar'])
@continue
@else
<li>{{$meta['pseudo']}}</li>
@endif
但呈現的html頁面顯示我
@continue。你知道怎麼做嗎?
解決辦法
在將提供的程式碼新增到routes.php後,是否清除了快取/編譯檢視檔案?如果沒有,請嘗試這樣做,因為只有在檢測到檢視中有更改時,blade才會重新編譯這些檢視。因此,如果在新增程式碼後沒有清除編譯後的檢視,則呈現的HTML中沒有任何更改。
如果不是這樣,請嘗試使用普通的舊regexp而不是blade::creatematcher,this好的定義將在一行程式中為您提供continue和break支援。
Blade::extend(function($value)
{
return preg_replace('/(\s*)@(break|continue)(\s*)/', '$1<?php $2; ?>$3', $value);
});
即使放在routes.php中,它也應該可以工作,不過最好放在單獨的檔案中(例如blade.php並將其包含在global.php中)。無論如何,必須在處理檢視之前載入它。