《PHP編程:詳解Laravel視圖間共享數(shù)據(jù)與視圖Composer》要點:
本文介紹了PHP編程:詳解Laravel視圖間共享數(shù)據(jù)與視圖Composer,希望對您有用。如果有疑問,可以聯(lián)系我們。
1、在視圖間共享數(shù)據(jù)
PHP編程
除了在單個視圖中傳遞指定數(shù)據(jù)之外,有時候需要在所有視圖中傳入同一數(shù)據(jù),即我們需要在不同視圖中共享數(shù)據(jù).要實現(xiàn)這一目的,需要使用視圖工廠的share
方法.PHP編程
全局幫助函數(shù)view
和response
類似,如果傳入?yún)?shù),則返回Illuminate\View\View
實例,不傳入?yún)?shù)則返回Illuminate\View\Factory
實例.所以我們可以通過在服務提供者的boot
方法中使用如下方式實現(xiàn)視圖間共享數(shù)據(jù):PHP編程
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { //視圖間共享數(shù)據(jù) view()->share('sitename','Laravel學院'); } /** * Register any application services. * * @return void */ public function register() { // } }
我們在routes.php
中定義兩個路由:PHP編程
Route::get('testViewHello',function(){ return view('hello'); }); Route::get('testViewHome',function(){ return view('home'); });
然后在resources/views
目錄下創(chuàng)建一個home.blade.php
視圖文件,內(nèi)容如下:PHP編程
{{$sitename}}首頁
再創(chuàng)建一個hello.blade.php
視圖文件:PHP編程
歡迎來到{{$sitename}}!
在瀏覽器中分別訪問http://laravel.app:8000/testViewHello
和http://laravel.app:8000/testViewHome
,則都能解析出$sitename
的值.PHP編程
2、視圖Composer
PHP編程
有時候我們想要在每次視圖渲染時綁定一些特定數(shù)據(jù)到視圖中,比如登錄用戶信息,這時候我們就要用到視圖Composer,視圖Composer通過視圖工廠的composer方法實現(xiàn).該方法的第二個回調(diào)參數(shù)支持基于控制器動作和閉包函數(shù)兩種方式.PHP編程
簡單起見,我們還是基于AppServiceProvider
,不去單獨創(chuàng)建服務提供者,這里我們傳遞閉包參數(shù)(控制器動作參考視圖文檔):PHP編程
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { //視圖間共享數(shù)據(jù) view()->share('sitename','Laravel學院'); //視圖Composer view()->composer('hello',function($view){ $view->with('user',array('name'=>'test','avatar'=>'/path/to/test.jpg')); }); } /** * Register any application services. * * @return void */ public function register() { // } }
修改hello.blade.php
視圖文件:PHP編程
歡迎來到{{$sitename}}!PHP編程
<h3>用戶信息</h3> 用戶名:{{$user['name']}}<br> 用戶頭像:{{$user['avatar']}}
在瀏覽器中訪問http://laravel.app:8000/testViewHello
,輸出內(nèi)容如下:PHP編程
歡迎來到Laravel學院! 用戶信息 用戶名:test 用戶頭像:/path/to/test.jpg
你也可以傳遞數(shù)據(jù)到多個視圖:PHP編程
view()->composer(['hello','home'],function($view){ $view->with('user',array('name'=>'test','avatar'=>'/path/to/test.jpg')); });
甚至所有視圖(使用通配符*):PHP編程
view()->composer('*',function($view){ $view->with('user',array('name'=>'test','avatar'=>'/path/to/test.jpg')); });
以上就是Laravel視圖間共享數(shù)據(jù)及視圖Composer的詳細內(nèi)容,希望本文對大家學習Laravel有所幫助.PHP編程
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/4821.html