Laravel 自定义视图组件
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
更多Laravel相关技术文章,请访问Laravel框架入门教程栏目进行学习!
以上是Laravel 自定义视图组件的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Laravel邮件发送失败时的退信代码获取方法在使用Laravel开发应用时,经常会遇到需要发送验证码的情况。而在实�...

Laravel计划任务运行无响应排查在使用Laravel的计划任务调度时,不少开发者会遇到这样的问题:schedule:run...

在dcatadmin(laravel-admin)中如何实现自定义点击添加数据的表格功能在使用dcat...

Laravel - 转储服务器 - Laravel 转储服务器随 Laravel 5.7 版本一起提供。以前的版本不包括任何转储服务器。转储服务器将成为 laravel/laravel Composer 文件中的开发依赖项。

Laravel框架中Redis连接的共享与select方法的影响在使用Laravel框架和Redis时,开发者可能会遇到一个问题:通过配置...

在Laravel多租户扩展包stancl/tenancy中自定义租户数据库连接使用Laravel多租户扩展包stancl/tenancy构建多租户应用时,...

Laravel - Action URL - Laravel 5.7 引入了一项名为“可调用操作 URL”的新功能。此功能类似于 Laravel 5.6 中的功能,即在操作方法中接受字符串。 Laravel 5.7 引入新语法的主要目的是直接
