将变量传递给Laravel中的多个视图 [英] Pass variables to multiple view in laravel

查看:63
本文介绍了将变量传递给Laravel中的多个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to pass a variable to multiple view bu when i use share method in View. Its says the share method isn't find on View.

你怎么说我用它,我也尝试作曲家,但是无论我如何尝试都行不通,你能给我这个动作的简单例子吗?

How you say i use it and i try the composer either but no matter how i try it can't work could you give me simple example of this action

我的控制器 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');

你有什么建议?

推荐答案

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

You can make a variable accessible in multiple views using one of these methods for example:

AppServiceProvider(参考: https://laravel.com/docs/5.6/providers )与ViewComposer(参考: https://laravel.com/docs/master/views#查看撰写者)

AppServiceProvider ( reference: https://laravel.com/docs/5.6/providers ) with ViewComposer ( reference: https://laravel.com/docs/master/views#view-composers )

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

You'll need to add to your ServiceProvider boot() method something similar to this:

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

或在控制器内部:

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

这篇关于将变量传递给Laravel中的多个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆