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
更多Laravel相干技术文章,请接见Laravel框架入门教程栏目举行进修!
以上就是Laravel 自定义视图组件的细致内容,更多请关注ki4网别的相干文章!