Laravel视图组件共享数据

2017-11-23  本文已影响0人  老王谈编程

做项目时会共享一些数据,比如布局文件中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()
    {
        //
    }
}

<?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,
],
<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>
上一篇 下一篇

猜你喜欢

热点阅读