Laravel 5.1:将数据传递到View Composer [英] Laravel 5.1 : Passing Data to View Composer

查看:59
本文介绍了Laravel 5.1:将数据传递到View Composer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Laravel 5.1中使用视图作曲家:太好了. 但是如何将参数传递给View Composer ?

I'm using view composers in Laravel 5.1: nice. But how can I pass parameters to a view composer?

在我的情况下,我将周信息(上周,当前,下周(包括日期))发送给使用view view作词器的视图.当前星期是可变的,不仅可以从网址中获取,还可以从控制器中获取.

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.

public function compose(View $view)
{
   // I need a parameter here (integers)
}

推荐答案

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

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类

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
    } );
}

控制器

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...
}

这篇关于Laravel 5.1:将数据传递到View Composer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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