做项目时会共享一些数据,比如布局文件中layouts/_sidebar.blade.php的菜单数据在每个页面都会显示,那么在laravel中就可以使用视图组件
$ php artisan make:provider ComposerServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
// 需要绑定数据的模板文件
view()->composer('layouts._sidebar', 'App\Http\ViewComposers\MenuComposer');
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
- 创建app/Http/ViewComposer/MenuComposer.php
<?php
namespace App\Http\ViewComposers;
use Illuminate\Contracts\View\View;
class MenuComposer
{
protected $menus;
public function __construct()
{
$this->menus = [
route('students.index') => '学生列表',
route('students.create') => '新增学生',
];
}
// 将数据渲染到视图中
public function compose(View $view)
{
// 渲染数据
$view->with('menus', $this->menus);
}
}
'providers' => [
/*
* Application Service Providers...
*/
App\Providers\ComposerServiceProvider::class,
],
- 视图文件中读取:resource/views/layouts/_header.blade.php
<div class="col-md-3">
<div class="list-group">
@if(isset($menus) && count($menus) > 0)
@foreach($menus as $key=>$menu)
<a href="{{ $key }}" class="list-group-item @if(\Request::url() === $key) active @endif">{{ $menu }}</a>
@endforeach
@endif
</div>
</div>