Laravel 5 - 所有模板中都可用的全局 Blade 视图变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29715813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5 - global Blade view variable available in all templates
提问by Limon Monte
How can I in Laravel 5 make global variable which will be available in all Blade templates?
我如何在 Laravel 5 中创建可在所有 Blade 模板中使用的全局变量?
回答by Emeka Mbah
Option 1:
选项1:
You can use view::share()
like so:
你可以view::share()
像这样使用:
<?php namespace App\Http\Controllers;
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');
}
}
Option 2:Use a composer:
选项 2:使用作曲家:
- Create a composer file at
app\Composers\HomeComposer.php
- 在以下位置创建作曲家文件
app\Composers\HomeComposer.php
NB: create app\Composers
if it does not exists
注意:app\Composers
如果不存在则创建
<?php namespace App\Composers;
class HomeComposer
{
public function compose($view)
{
//Add your variables
$view->with('variable1', 'I am Data')
->with('variable2', 'I am Data 2');
}
}
Then you can attached the composer to any view by doing this
然后您可以通过执行此操作将作曲家附加到任何视图
<?php namespace App\Http\Controllers;
use View;
class HomeController extends Controller{
public function __construct(){
View::composers([
'App\Composers\HomeComposer' => ['home'] //attaches HomeComposer to home.blade.php
]);
}
public function Index(){
return view('home');
}
}
Option 3:Add Composer to a Service Provider, In Laravel 5 I prefer having my composer in App\Providers\ViewServiceProvider
选项 3:将 Composer 添加到服务提供者,在 Laravel 5 中,我更喜欢将我的 Composer 放在 App\Providers\ViewServiceProvider 中
Create a composer file at
app\Composers\HomeComposer.php
Add HomeComposer to App\Providers\ViewServiceProvider
在以下位置创建作曲家文件
app\Composers\HomeComposer.php
将 HomeComposer 添加到 App\Providers\ViewServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use View;
use App\Composers\HomeComposer;
use Illuminate\Support\Facades\Blade;
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);
}
}
回答by Nicolas
Create a new Service Provider as suggested in here
Add your new Service Provider to the configuration file (config/app.php).
将您的新服务提供者添加到配置文件 (config/app.php)。
In the boot method of your new Service Provider use:
在新服务提供商的引导方法中使用:
View::share( 'something_cool', 'this is a cool shared variable' );
Now you are ready to use $something_cool in all of your views.
现在您已准备好在所有视图中使用 $something_cool。
Hope this helps.
希望这可以帮助。
回答by sha-1
回答by ArjanSchouten
You can do this with view composers. View composers are executed when a template is loaded. You can pass in a Closure with additional functionality for that view. With view composers you can use wildcards. To make a view composer for every view just use a *
.
您可以使用视图作曲家来做到这一点。加载模板时执行视图编辑器。您可以为该视图传递具有附加功能的闭包。使用视图作曲家,您可以使用通配符。要为每个视图制作一个视图合成器,只需使用*
.
View::composer('*', function($view)
{
$view->with('variable','Test value');
});
You can also do this without a closure as you can see in the docs.
您也可以在没有闭包的情况下执行此操作,如您在文档中所见。
View::composer('*', 'App\Http\ViewComposers\ProfileComposer');
The profile composer class must have a compose method.
配置文件 Composer 类必须有一个 compose 方法。
View composers are executed when a view is rendered. Laravel has also view creators. These are executed when a view is instantiated.
在渲染视图时执行视图编辑器。Laravel 也有视图创建者。这些是在实例化视图时执行的。
You can also choose to use a BaseController
with a setupLayout method. Then every view which you will load is loaded through the setupLayout method which adds some additional data. However, by using view composers you're pretty sure that the code is executed. But with the BaseController approach you've more flexibility because you can skip the loading of the extra data.
您还可以选择将 aBaseController
与 setupLayout 方法一起使用。然后您将加载的每个视图都通过 setupLayout 方法加载,该方法添加了一些额外的数据。但是,通过使用视图编辑器,您可以非常确定代码已被执行。但是使用 BaseController 方法,您可以获得更大的灵活性,因为您可以跳过额外数据的加载。
EDIT: As mentioned by Nic Gutierrez you can also use view share.
编辑:正如 Nic Gutierrez 所提到的,您还可以使用视图共享。
回答by Jodeveloper8
Also, you can do this in the Route.php
file:
此外,您可以在Route.php
文件中执行此操作:
view()->share('variableName', $variable);
回答by Ehab Elzeny
and you can give array not just View::share('key', 'value');
can put array like View::share(['key'=>'value','key'=>'value'])
你可以给数组而不只是View::share('key', 'value');
可以把数组像View::share(['key'=>'value','key'=>'value'])
回答by Gabi Dj
I would rather use middleware with the view()
facade helper. (Laravel 5.x)
我宁愿将中间件与view()
门面助手一起使用。(Laravel 5.x)
Middleware is easier to mantain and does not make a mess in the controllers class tree.
中间件更容易维护并且不会在控制器类树中造成混乱。
Steps
脚步
Create the Middleware
创建中间件
/app/Http/Middleware/TimezoneReset.php
/app/Http/Middleware/TimezoneReset.php
To create a middleware you can run php artisan make:middleware GlobalTimeConfig
要创建一个中间件,您可以运行 php artisan make:middleware GlobalTimeConfig
share()
the data you need shared
share()
您需要共享的数据
<?php
namespace App\Http\Middleware;
use Closure;
class GlobalTimeConfig
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$time_settings = [
'company_timezone' => 'UTC',
'company_date_format' => 'Y-m-d H:i:s',
'display_time' => true,
];
view()->share('time_settings', $time_settings);
return $next($request);
}
}
Register the newly created middleware
注册新创建的中间件
Add the middleware to your middleware route group as per example below
按照下面的示例将中间件添加到您的中间件路由组
/app/Http/Kernel.php
/app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\GlobalTimeConfig::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
Access data from templates
从模板访问数据
Access the data from any template with the given key in the View::share() method call
在 View::share() 方法调用中使用给定键访问任何模板中的数据
eg.:
例如。:
Company timezone: {{ $time_settings['company_timezone'] }}
EDIT: Nic Gutierrez's Service Provider answer might be a better (or the best) solution.
编辑:Nic Gutierrez 的服务提供商答案可能是更好(或最好)的解决方案。
回答by Arshad Jilani
You can add in Controller.php
file:
您可以在Controller.php
文件中添加:
use App\Category;
And then:
进而:
class Controller extends BaseController {
public function __construct() {
$categories = Category::All();
\View::share('categories', $categories);
}
}
回答by Jeff
you can flash it into the session, you can define it in the .env file (static vars)
您可以将其闪存到会话中,您可以在 .env 文件中定义它(静态变量)