Laravel 5 - 所有模板中都可用的全局 Blade 视图变量 [英] Laravel 5 - global Blade view variable available in all templates
本文介绍了Laravel 5 - 所有模板中都可用的全局 Blade 视图变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何在 Laravel 5 中创建可在所有 Blade 模板中使用的全局变量?
How can I in Laravel 5 make global variable which will be available in all Blade templates?
推荐答案
选项 1:
你可以像这样使用view::share()
:
<?php namespace AppHttpControllers;
use View;
//You can create a BaseController:
class BaseController extends Controller {
public $variable1 = "I am Data";
public function __construct() {
$variable2 = "I am Data 2";
View::share ( 'variable1', $this->variable1 );
View::share ( 'variable2', $variable2 );
View::share ( 'variable3', 'I am Data 3' );
View::share ( 'variable4', ['name'=>'Franky','address'=>'Mars'] );
}
}
class HomeController extends BaseController {
//if you have a constructor in other controllers you need call constructor of parent controller (i.e. BaseController) like so:
public function __construct(){
parent::__construct();
}
public function Index(){
//All variable will be available in views
return view('home');
}
}
选项 2:使用作曲家:
- 在
appComposersHomeComposer.php
创建一个 Composer 文件
- Create a composer file at
appComposersHomeComposer.php
注意:如果 appComposers
不存在,则创建它
NB: create appComposers
if it does not exists
<?php namespace AppComposers;
class HomeComposer
{
public function compose($view)
{
//Add your variables
$view->with('variable1', 'I am Data')
->with('variable2', 'I am Data 2');
}
}
然后您可以通过执行此操作将作曲家附加到任何视图
<?php namespace AppHttpControllers;
use View;
class HomeController extends Controller{
public function __construct(){
View::composers([
'AppComposersHomeComposer' => ['home'] //attaches HomeComposer to home.blade.php
]);
}
public function Index(){
return view('home');
}
}
选项 3:将 Composer 添加到服务提供者,在 Laravel 5 中,我更喜欢将我的 Composer 放在 AppProvidersViewServiceProvider
Option 3: Add Composer to a Service Provider, In Laravel 5 I prefer having my composer in AppProvidersViewServiceProvider
在
appComposersHomeComposer.php
将 HomeComposer 添加到 AppProvidersViewServiceProvider
Add HomeComposer to AppProvidersViewServiceProvider
<?php
namespace AppProviders;
use IlluminateSupportServiceProvider;
use View;
use AppComposersHomeComposer;
use IlluminateSupportFacadesBlade;
class ViewServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//add to all views
view()->composer('*', HomeComposer::class);
//add to only home view
//view()->composer('home', HomeComposer::class);
}
}
这篇关于Laravel 5 - 所有模板中都可用的全局 Blade 视图变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文