laravel 的視圖合成器可將數據與指定視圖綁定在一起,避免了重復編寫代碼。
View::composer('profile',?'AppHttpViewComposersProfileComposer');
由于數據的生成和渲染是分開進行的,理解起來不夠直觀。因此,可以采用視圖組件的方式將兩者進行封裝。
<?php namespace AppViewComponents; use IlluminateContractsSupportHtmlable; use IlluminateHttpRequest; use IlluminateSupportFacadesView; class ExampleComponent implements Htmlable { private $color; private $request; public function __construct(Request $request, string $color) { $this->color?=?$color; ????????$this->request?=?$request; ????} ????public?function?toHtml() ????{??? ????????return?View::make('example') ????????????->with('color',?$this->color) ????????????->render(); ????} }
在視圖中使用
{{?app()->makeWith(AppViewComponentsExampleComponent::class,['color'?=>?'green'])->toHtml()?}}
封裝指令
Blade::directive('render',?function?($expression)?{ ????list($class,?$params)?=?explode(',',?$expression,?2); ????$class?=?"AppViewComponents".trim($class,?''"?'); ????return?"<?php echo app()->makeWith('$class',?$params)->toHtml();??>"; });
使用指令
@render('ExampleComponent',?['color'?=>?'green'])
參考資料
spatie/laravel-view-components:?A?better?way?to?connect?data?with?view?rendering?in?Laravel Introducing?View?Components?in?Laravel,?an?alternative?to?View?Composers?-?Laravel?News
更多Laravel相關技術文章,請訪問Laravel框架入門教程欄目進行學習!
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END