Laravel 5.1:将数据传递给 View Composer
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34153072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.1 : Passing Data to View Composer
提问by schellingerht
I'm using view composers in Laravel 5.1: nice. But how can I pass parameters to a view composer?
我在 Laravel 5.1 中使用视图作曲家:很好。但是如何将参数传递给视图作曲家?
In my case I send week info (previous, current, next week, including the dates) to my view with de view composer. The current week is variable, not only from an url, but also from the controller.
就我而言,我使用 de view composer 将周信息(上一周、当前、下周,包括日期)发送到我的视图中。当前周是可变的,不仅来自 url,还来自控制器。
public function compose(View $view)
{
// I need a parameter here (integers)
}
回答by Moppo
If you have to pass parameters from a controller to a view composer, you can create a wrapper class for the composer and pass data to it whenever needed. Then, when you're done setting up you data, you can compose the view:
如果您必须将参数从控制器传递给视图编写器,您可以为编写器创建一个包装类,并在需要时将数据传递给它。然后,当您完成数据设置后,您可以编写视图:
ComposerWrapper class
ComposerWrapper 类
public function __construct(array $data)
{
$this->data = $data;
}
public function compose()
{
$data = $this->data;
View::composer('partial_name', function( $view ) use ($data)
{
//here you can use your $data to compose the view
} );
}
Controller
控制器
public function index()
{
//get the data you need
$data = ['first_value' = 1];
//pass the data to your wapper class
$composerWrapper = new ComposerWrapper( $data );
//this will compose the view
$composerWrapper->compose();
//other code...
}
回答by Elisha Senoo
All the data you pass to your view in the controller will be available in the view controller. Use the getData
method on the view instance like this:
您传递给控制器中的视图的所有数据都将在视图控制器中可用。getData
在视图实例上使用该方法,如下所示:
$view->getData()["current_week"];
In your particular case, you can do this:
在您的特定情况下,您可以这样做:
public function compose(View $view)
{
$current_week = $view->getData()["current_week"];
//use $current_week as desired
}
You can also get the data in the route (route parameters) from the request like this:
您还可以从请求中获取路由中的数据(路由参数),如下所示:
request()->route()->getParameter('week_number');