Laravel:传递默认变量以查看 [英] Laravel: Passing default variables to view

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

问题描述

在Laravel中,我们几乎都以相同的方式将数据传递到视图中

In Laravel, we all pass data to our view in pretty much the same way

$data = array(
    'thundercats' => 'Hoooooooooooh!'
);
return View::make('myawesomeview', $data);

但是有什么方法可以向视图中添加默认变量,而不必在$data中一遍又一遍地声明它?如果站点需要,这对于重复诸如用户名,PHP逻辑甚至CSS样式之类的变量将非常有帮助.

But is there some way to add default variables to the view without having to declare it over and over in $data? This would be very helpful for repeating variables such as usernames, PHP logic, and even CSS styles if the site demands it.

推荐答案

使用View Composers

视图编写器是在以下情况下调用的回调或类方法: 视图已创建.如果您有要绑定到给定视图的数据 每次在整个应用程序中创建该视图时,都会创建一个视图 作曲家可以将该代码组织到一个位置.所以, 视图撰写者的功能可能类似于视图模型"或演示者".

View composers are callbacks or class methods that are called when a view is created. If you have data that you want bound to a given view each time that view is created throughout your application, a view composer can organize that code into a single location. Therefore, view composers may function like "view models" or "presenters".

定义View Composer:

View::composer('profile', function($view)
{
    $view->with('count', User::count());
});

现在,每次创建配置文件视图时,计数数据都将绑定到该视图.在您的情况下,可能是id:

Now each time the profile view is created, the count data will be bound to the view. In your case, it could be for id :

    View::composer('myawesomeview', function($view)
    {
        $view->with('id', 'someId');
    });

因此,每次使用myawesomeview视图创建$id时,该视图均可使用:

So the $id will be available to your myawesomeview view each time you create the view using :

View::make('myawesomeview', $data);

您还可以将视图编辑器一次附加到多个视图:

You may also attach a view composer to multiple views at once:

View::composer(array('profile','dashboard'), function($view)
{
    $view->with('count', User::count());
});

如果您希望使用基于类的作曲家,那么它将提供通过应用程序解决的好处 IoC容器,您可以这样做:

If you would rather use a class based composer, which will provide the benefits of being resolved through the application IoC Container, you may do so:

View::composer('profile', 'ProfileComposer');

View Composer类的定义应如下:

A view composer class should be defined like so:

class ProfileComposer {
    public function compose($view)
    {
        $view->with('count', User::count());
    }
}

文档,您可以 查看全文

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