如何将数据注入到布局中? [英] How do inject data into a layout?

查看:45
本文介绍了如何将数据注入到布局中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据注入到布局(而不是子视图)中,但是我还没有找到任何看起来可行的方法.

I am trying to inject data into a layout (not the sub-view), but I have not found any method that seems practical.

这是我目前所知道的两种方法来完成此任务.为了简单起见,我将要注入的数据是页面标题.

These are the two ways I currently know of to accomplish this. The data I will be injecting is the page title, for simplicity.

// app/controllers/HomeController.php

protected $layout = 'main';

public function index()
{
    $this->layout->title = 'Page Title';
    $this->layout->content = View::make('home');
}


// app/views/layout.blade.php
...
<title>{{ $title }}</title>
...

方法2

// app/views/home.blade.php
...
@section('title')
    Page Title
@stop
...


// app/views/layout.blade.php

...
<title>@yield('title')</title>
...

再一次,这些方法都不是理想的方法,但是到目前为止,我还没有看到更好的方法.我觉得Laravel 必须有内置的方法来处理这个问题...

Once again, neither of these methods seem to be ideal, but I haven't seen a better method so far. I feel like Laravel must have some method built in to handle this...

推荐答案

您可以编辑 BaseController 中的 setupLayout 方法,将数据直接传递给 View::make 调用.

You can edit the setupLayout method in the BaseController to pass the data directly to the View::make call.

protected function setupLayout()
{
    if(!is_null($this->layout))
    {
        $data = array(
            'title' => 'Page Title'
        );

        $this->layout = View::make($this->layout, $data);
    }
}

或者,您可以更改setupLayout方法以访问$ this-> layoutData:

Alternatively, you could change the setupLayout method to access $this->layoutData:

protected function setupLayout()
{
    if(!is_null($this->layout))
    {
        $this->layout = View::make($this->layout, $this->layoutData);
    }
}

然后在您的实际控制器中设置以下内容:

Then set the following in your actual controller:

$this->layoutData = array('title' => 'Page Title');

这篇关于如何将数据注入到布局中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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