Laravel 的檢視合成器可將資料與指定檢視繫結在一起,避免了重複編寫程式碼。
View::composer('profile', 'App\Http\View\Composers\ProfileComposer');
由於資料的生成和渲染是分開進行的,理解起來不夠直觀。因此,可以採用檢視元件的方式將兩者進行封裝。
<?php
namespace App\ViewComponents;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
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(App\ViewComponents\ExampleComponent::class,['color' => 'green'])->toHtml() }}
封裝指令
Blade::directive('render', function ($expression) {
list($class, $params) = explode(',', $expression, 2);
$class = "App\\ViewComponents\\".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
本作品採用《CC 協議》,轉載必須註明作者和本文連結