【问题标题】:Pass variables to multiple view in laravel将变量传递给laravel中的多个视图
【发布时间】:2019-01-21 13:33:25
【问题描述】:

当我在视图中使用共享方法时,我想将一个变量传递给多个视图。它说在 View 上找不到 share 方法。

你怎么说我使用它,我也尝试作曲家,但无论我怎么尝试它都无法工作,你能给我这个动作的简单例子

我的控制器categorycontroller.php

public function site(){
    $data =  array();
    $data['subcategories']  =  SubCategory::all();
    $data['categories']     =  Category::all();
    return view('template.sitemap',compact("data"));
}

我的路线web.php

Route::get('/404.html', function () {
    return view('template/404');
})->name('404.html');

Route::get('404.html','CategoryController@site')->name('404');

Route::get('/sitemap.html', function () {
    return view('template/sitemap');
})->name('sitemap.html');

Route::get('sitemap.html','CategoryController@site')->name('sitemap');

你有什么建议?

【问题讨论】:

  • 我尝试使用 View Share 方法,但它没有在 view 中定义。
  • 你的 Laravel 版本是什么?

标签: laravel laravel-routing laravel-blade laravel-views


【解决方案1】:

您可以使用以下方法之一使变量在多个视图中可访问,例如:

AppServiceProvider(参考:https://laravel.com/docs/5.6/providers)和 ViewComposer(参考:https://laravel.com/docs/master/views#view-composers

您需要在 ServiceProvider boot() 方法中添加类似于以下内容的内容:

public function boot()
{
    View::share('variable_name', 'some_value_here');
}

或者在控制器内部:

public function __construct() {
  $something = 'just a test';
  View::share('something', $something);
}

【讨论】:

  • 我尝试做你说的事情,但在我运行项目之前我得到了这个错误> php artisan serve 在 Macroable.php 第 75 行:方法 Illuminate\View\View::share 不存在。
  • 你使用的是什么 Laravel 版本?你应该使用这个特性:使用 Illuminate\Support\Facades\View;
  • laravel 5.6 版本,但我收到“方法 Illuminate\View\View::share 不存在。”
  • View 不是Illuminate\View\View 它是门面,总是ViewIlluminate\Support\Facades\View
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-30
  • 1970-01-01
  • 1970-01-01
  • 2019-01-21
  • 2019-07-06
  • 2011-10-01
  • 2015-01-11
相关资源
最近更新 更多