[英]Global variable in Laravel Blade
我是Laravel服務提供商的新手,最近遇到了一個問題。 我正在嘗試從所有視圖(全局)中的服務提供商訪問變量。 該變量采用json格式。 這是我的服務提供商
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ExternalVarServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application ExternalVarServiceProvider.
*
* @return void
*/
public function boot()
{
$url = "json-source-url";
$json = json_decode(file_get_contents($url), true);
$var = $json["array_index"];
//var should be global to all blade files, app.blade.php is main templ
View::share( 'app', 'var' );
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
謝謝您的閱讀,Pat :)
您做得對,但是您只需要在以下位置更改服務提供商中的這一行:
View::share( 'app', 'var' );
至
View::share( 'app', $var );
在您看來,您可以像這樣使用它
{{$app}}
您還可以像這樣在服務提供商中傳遞一個數組:
\View::share( ['app'=> $var,'app2'=>$var2] );
請注意,根據文檔 ,share方法接受鍵和值,因此app不是視圖名稱,它是您共享值的鍵
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.