Laravel 5.1:将数据传递给View Composer

sch*_*rht 2 php view laravel laravel-5 laravel-5.1

我在Laravel 5.1中使用视图作曲家:很好.但是如何将参数传递给视图编辑器

在我的情况下,我使用de view composer将周信息(上一个,当前,下周,包括日期)发送到我的视图.本周是可变的,不仅来自网址,还来自控制器.

public function compose(View $view)
{
   // I need a parameter here (integers)
}
Run Code Online (Sandbox Code Playgroud)

Mop*_*ppo 7

如果必须将参数从控制器传递给视图编辑器,则可以为编写器创建包装类,并在需要时将数据传递给它.然后,当您完成数据设置后,您可以撰写视图:

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
    } );
}
Run Code Online (Sandbox Code Playgroud)

调节器

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...
}
Run Code Online (Sandbox Code Playgroud)


Eli*_*noo 6

您传递给控制器​​中视图的所有数据都将在视图控制器中可用。getData在视图实例上使用该方法,如下所示:

$view->getData()["current_week"];
Run Code Online (Sandbox Code Playgroud)

在您的特定情况下,您可以这样做:

public function compose(View $view)
{
   $current_week = $view->getData()["current_week"];
   //use $current_week as desired 
}
Run Code Online (Sandbox Code Playgroud)

您还可以从请求中获取路由中的数据(路由参数),如下所示:

request()->route()->getParameter('week_number');
Run Code Online (Sandbox Code Playgroud)