您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
使用view-composer来实现多视图数据传递(多个视图的公共部分变量的优雅实现)
发布时间:2024-11-11 22:10:05编辑:雪饮阅读()
-
View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location. View composers may prove particularly useful if the same view is returned by multiple routes or controllers within your application and always needs a particular piece of data.
laravel11中view composer是实现多个视图所共用的一些变量的更优雅的实现。
首先我们需要在服务提供商进行启用,例如Y:\root\example-app\app\Providers\AppServiceProvider.php中的boot方法
中我启用如
Facades\View::composer('viewa', function (View $view) {
$view->with('EmailContent', 'a@qq.com');
});
当然前提是需要导入相关命名空间
use Illuminate\Support\Facades;
use Illuminate\View\View;
这里将在名为viewa的视图中注入了可用变量'EmailContent',且其内容为'a@qq.com
那么在inertia架构下,我创建视图如
Y:\root\example-app\resources\views\viewa.blade.php
<div>
this is view a,email content: {{ $EmailContent }}
</div>
那么在web.php中定义一个路由如
Route::get('/dashboard/viewa', [DashboardController::class, 'viewa'])->name('dashboard.viewa');
该路由让Dashboard的viewa方法去返回viewa视图。
所以Dashboard的viewa方法实现如
public function viewa(){
return view('viewa');
}
那么此时访问路由如
http://localhost/dashboard/viewa
就会在网页中呈现内容如:
this is view a,email content: a@qq.com
那么这里只是在服务提供商中用view composer仅启用了一个视图的注入变量。
其实我们还可以像是这样用数组的方式同时为多个视图进行可用变量的定义
Facades\View::composer(['viewb','viewc'], function (View $view) {
$view->with('EmailContent', 'bc@qq.com');
});
那么假定路由viewb和路由viewc分别如
http://localhost/dashboard/viewb
http://localhost/dashboard/viewc
那么此时他们也在web.php中定义了
Route::get('/dashboard/viewb', [DashboardController::class, 'viewb'])->name('dashboard.viewb');
Route::get('/dashboard/viewc', [DashboardController::class, 'viewc'])->name('dashboard.viewc');
控制器的实现中也分别是
public function viewb(){
return view('viewb');
}
public function viewc(){
return view('viewc');
}
并且创建了viewb.blade.php如
<div>
this is view b,email content: {{ $EmailContent }}
</div>
以及viewc.blade.php如
<div>
this is view c,email content: {{ $EmailContent }}
</div>
那么上面新增这两个路由都将返回内容于网页中分别如
this is view b,email content: bc@qq.com
this is view c,email content: bc@qq.com
为了方便对比,我们也可以直接在之前的Dashboard.vue组件中直接用iframe将这三个路由请求结果简单的整合一起。
<div>
<h1 style="text-align: center;">View Composer</h1>
<div style="display: flex;justify-content: center;">
<iframe src="/dashboard/viewa"></iframe>
<iframe src="/dashboard/viewb"></iframe>
<iframe src="/dashboard/viewc"></iframe>
</div>
</div>
效果实现如
本期词汇
bound 捆绑;使团结
prove 显示出
particularly 非常,尤其
关键字词:view,composer