詳解Laravel視圖間共享數(shù)據(jù)與視圖Composer
1、在視圖間共享數(shù)據(jù)
除了在單個視圖中傳遞指定數(shù)據(jù)之外,有時候需要在所有視圖中傳入同一數(shù)據(jù),即我們需要在不同視圖中共享數(shù)據(jù)。要實現(xiàn)這一目的,需要使用視圖工廠的share
方法。
全局幫助函數(shù)view
和response
類似,如果傳入?yún)?shù),則返回Illuminate\View\View
實例,不傳入?yún)?shù)則返回Illuminate\View\Factory
實例。所以我們可以通過在服務提供者的boot
方法中使用如下方式實現(xiàn)視圖間共享數(shù)據(jù):
<?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
中定義兩個路由:
Route::get('testViewHello',function(){ return view('hello'); }); Route::get('testViewHome',function(){ return view('home'); });
然后在resources/views
目錄下創(chuàng)建一個home.blade.php
視圖文件,內(nèi)容如下:
{{$sitename}}首頁
再創(chuàng)建一個hello.blade.php
視圖文件:
歡迎來到{{$sitename}}!
在瀏覽器中分別訪問http://laravel.app:8000/testViewHello
和http://laravel.app:8000/testViewHome
,則都能解析出$sitename
的值。
2、視圖Composer
有時候我們想要在每次視圖渲染時綁定一些特定數(shù)據(jù)到視圖中,比如登錄用戶信息,這時候我們就要用到視圖Composer,視圖Composer通過視圖工廠的composer方法實現(xiàn)。該方法的第二個回調(diào)參數(shù)支持基于控制器動作和閉包函數(shù)兩種方式。
簡單起見,我們還是基于AppServiceProvider
,不去單獨創(chuàng)建服務提供者,這里我們傳遞閉包參數(shù)(控制器動作參考視圖文檔):
<?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
視圖文件:
歡迎來到{{$sitename}}!
<h3>用戶信息</h3> 用戶名:{{$user['name']}}<br> 用戶頭像:{{$user['avatar']}}
在瀏覽器中訪問http://laravel.app:8000/testViewHello
,輸出內(nèi)容如下:
歡迎來到Laravel學院! 用戶信息 用戶名:test 用戶頭像:/path/to/test.jpg
你也可以傳遞數(shù)據(jù)到多個視圖:
view()->composer(['hello','home'],function($view){ $view->with('user',array('name'=>'test','avatar'=>'/path/to/test.jpg')); });
甚至所有視圖(使用通配符*):
view()->composer('*',function($view){ $view->with('user',array('name'=>'test','avatar'=>'/path/to/test.jpg')); });
以上就是Laravel視圖間共享數(shù)據(jù)及視圖Composer的詳細內(nèi)容,希望本文對大家學習Laravel有所幫助。
相關文章
PHP中set error handler函數(shù)用法小結(jié)
set_error_handler() 函數(shù)設置用戶自定義的錯誤處理函數(shù)。該函數(shù)用于創(chuàng)建運行時期間的用戶自己的錯誤處理方法。該函數(shù)會返回舊的錯誤處理程序,若失敗,則返回 null2015-11-11thinkphp框架表單數(shù)組實現(xiàn)圖片批量上傳功能示例
這篇文章主要介紹了thinkphp框架表單數(shù)組實現(xiàn)圖片批量上傳功能,結(jié)合實例形式分析了js前端圖片上傳與后臺thinkPHP文件處理相關操作技巧,需要的朋友可以參考下2020-04-04php實現(xiàn)根據(jù)IP地址獲取其所在省市的方法
今天,就討論一下在PHP中如何獲取用戶IP地址、PHP根據(jù)IP判斷用戶所在城市以及PHP根據(jù)IP實現(xiàn)城市切換或跳轉(zhuǎn)的問題。2015-04-04PHP isset empty函數(shù)相關面試題及解析
這篇文章主要介紹了PHP isset empty函數(shù)相關面試題及解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-12-12