Laravel 自定義視圖組件

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-&gt;request?=?$request; ????} ????public?function?toHtml() ????{??? ????????return?View::make('example') ????????????-&gt;with('color',?$this-&gt;color) ????????????-&gt;render(); ????} }

在視圖中使用

{{?app()-&gt;makeWith(AppViewComponentsExampleComponent::class,['color'?=&gt;?'green'])-&gt;toHtml()?}}

封裝指令

Blade::directive('render',?function?($expression)?{ ????list($class,?$params)?=?explode(',',?$expression,?2); ????$class?=?"AppViewComponents".trim($class,?''"?'); ????return?"<?php  echo app()->makeWith('$class',?$params)-&gt;toHtml();??&gt;"; });

使用指令

@render('ExampleComponent',?['color'?=&gt;?'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
喜歡就支持一下吧
點贊13 分享