簡體   English   中英

Laravel 5.4:將變量解析為視圖的最佳實踐

[英]Laravel 5.4 : Best practice to parse variable to a view

例如,我想在默認視圖中添加一個變量(default.blade.php)

我當然可以將變量直接定義到視圖文件中,如下所示:

@php ($user = Sentinel::getUser())

但是不建議這樣做。

我應該在AppServiceProvider.php上添加它嗎? https://laravel.com/docs/5.4/views#sharing-data-with-all-views

但是用哪個電話呢? 像這樣 :

public function boot()
    { $user = Sentinel::getUser(); }

得到:未定義的變量:用戶

public function boot()
    { View::share('user', Sentinel::getUser()); }

此嘗試試圖獲取非對象的屬性,因此Sentinel並未真正聲明

或在控制器中

public function __construct()
    {
        //user
        $user = Sentinel::getUser();
        view()->share('user',$user);            

    }

我也在我的控制器中嘗試

public function boot()
    {
        return view('layouts/default')->with('user', Sentinel::getUser(););
    }

要么

public function boot()    {
        view()->composer('layouts.default', function($view)     {
            $view->with('user', Sentinel::getUser());

        });     
    }

仍然得到“未定義的變量:用戶”

這個想法是在服務提供商的啟動方法中調用View :: XXXXX。

最簡單的方法是在您的應用服務提供商內部的視圖上調用共享...這將使它可用於所有視圖...但是請注意何時解析此值,它會在啟動時解析...

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::share('key', 'value');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

您還可以創建一個視圖編輯器,該視圖編輯器將在呈現特定視圖或一組視圖之前運行...您可以為其提供視圖/類或視圖/關閉...將在視圖呈現之前對其進行評估...

綁定一個視圖作曲家類:

public function boot()
    {
        // Using class based composers...
        View::composer(
            'profile', 'App\Http\ViewComposers\ProfileComposer'
        );
}

或附加一個封蓋...,然后執行在該封蓋內啟動競爭的操作...

public function boot()
    {
        // Using Closure based composers...
        View::composer('dashboard', function ($view) {
            //
        });
}

您可以綁定到所有視圖,例如View :: share ...,但可以使用基於閉合的簡單組合器將評估推到視圖渲染之前。

        // Using Closure based composers...
        View::composer('dashboard', function ($view) {
            $view->with('user', Sentinel::getUser() );
        });

希望這可以幫助...

在您的控制器中,定義如下函數:

public function index() {
   $user = Sentinel::getUser();

   //The parameter of the view is your blade file relative to your directory
   //resources/views/default.blade.php
   return view('default')->with('user', $user);
}

在您的web.php(路由文件)中,添加此

//First parameter is the url, second is the controller/function
Route::get('/', 'YourControllerName@index');

現在在localhost中測試視圖[可選]

http://本地主機:8000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM