Blade 模板引擎 View Composer & 自定义指令

 

0. 传给全局模板变量方法 在boot() 中定义 ,  模板中随意使用  

view()->share('site', 'aocn's site')

 

1. view composer 定义在  AppServiceProvider boot() 方法中  (推荐)

view()->composer(['admin.index', 'admin.about' ], function($view){

  $view->with('site', 'aocn');

})

 

view()->composer('admin.*', function($view){

  $view->with('site', 'aocn');

})

 

2.view composer 自定义参数传递 (对 view 的 composer 进行拆分)

在 App\Http\ViewComposers\RecentPostsComposer.php

<?php

namespace App\Http\ViewComposers; 

use App\Post; 
use Illuminate\Contracts\View\View; 

class RecentPostsComposer 
{

    private $posts; 

    public function __construct(Post $posts) { 
        $this->posts = $posts; 
    }

    public function compose(View $view) { 
        $view->with('posts', ['a1', 'a2', 'a3', 'a4']);
        // $view->with('posts', $this->posts->recent());
    }

}

 

 

使用在 AppServiceProvider  root() 方法中

        view()->composer( 'partials.sidebar', \App\Http\ViewComposers\RecentPostsComposer::class );

 

 

 

 

 

  除非预设逻辑很复杂,否则推荐使用闭包函数方式来实现,一则简洁,二则减少了不必要的类初始化和方法调用对性能的损耗。

 

 

 

 

 

<?php

namespace App\Http\ViewComposers;

use App\Post;
use Illuminate\Contracts\View\View;

class RecentPostsComposer
{

private $posts;

public function __construct(Post $posts) {
$this->posts = $posts;
}

public function compose(View $view) {
$view->with('posts', ['a1', 'a2', 'a3', 'a4']);
// $view->with('posts', $this->posts->recent());
}

}


posted @ 2019-06-15 17:04  aocn  阅读(357)  评论(0)    收藏  举报