Laravel Blade 中的全局变量

Global variable in Laravel Blade

我是 Laravel 服务提供商的新手,我最近 运行 遇到了一个问题。我试图在所有视图(全局)中访问来自服务提供商的变量。该变量采用 json 格式。 这是我的 ServiceProvider

<?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()
      {
          //
      }
  }

感谢您的阅读,帕特 :)

你做的是对的,但你只需要在你的服务提供商中改变这一行从

View::share( 'app', 'var' );

View::share( 'app', $var );

在你看来你可以像这样使用它

{{$app}}

您还可以像这样在您的服务提供商中传递一个数组:

\View::share( ['app'=> $var,'app2'=>$var2] );

请注意,根据 documentation 共享方法接受键和值,因此 app 不是视图名称它的 key 您的共享价值