【问题标题】:Global variable in Laravel BladeLaravel Blade 中的全局变量
【发布时间】:2018-01-30 03:25:19
【问题描述】:

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

感谢您的阅读,帕特 :)

【问题讨论】:

    标签: php json global-variables laravel-blade


    【解决方案1】:

    你做对了,但你只需要在你的服务提供商中改变这条线

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

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

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

    {{$app}}
    

    你也可以像这样在你的服务提供者中传递一个数组:

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

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

    【讨论】:

    • 谢谢,我现在意识到 share 需要 var name 然后是 value,而不是 view-to-share-to then value。谢谢队友:)
    猜你喜欢
    • 2014-05-06
    • 2015-06-25
    • 2016-12-20
    • 2021-09-23
    • 1970-01-01
    • 2013-11-25
    • 2019-05-25
    相关资源
    最近更新 更多