Laravel很好地定义了控制器的默认布局 [英] Laravel define default layout from controller in good way

查看:82
本文介绍了Laravel很好地定义了控制器的默认布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Google搜索了两个小时,但没有找到答案.也许你可以帮忙.

I googled two hours, but not found answer. Maybe you can help.

当我在 MyController 中定义时:

class MyController extends Base_Controller {
    public $layout = 'layouts.default';

    public function get_index() {
        $entries = Entry::all();
        return View::make('entries.index')
            ->with('entries', $entries);
        }
    }
}

entries \ index.blade.php 中:

@section('content')
    <h1>Test</h1>
@endsection

并在 layouts \ default.blade.php 中:

<!DOCTYPE html>
<html>
<body>
    @yield('content')
</body>
</html>

什么都没有显示.而且我不明白为什么.当我在 MyController 中替换时,返回的部分为:

Nothing is displaying. And I don't understand why. When I am replacing in MyController return part with:

$this->layout->nest('content', 'entries.index', array(
    'entries' => $entries
));

然后一切正常,但是..看起来不干净,我不喜欢它.当在每个视图中添加@layout('layouts.default')时,一切也都很好,但不是DRY.例如,在RoR中,我不需要在Controller中执行此类操作.

Then all is working, but.. It looks not clean and I don't like it. When adding in every view @layout('layouts.default') all is working good too, but it is not DRY. For example, in RoR I don't need to do such things in Controller.

如何在MyController中定义一种布局并使用return View::make(我认为这是正确的方法),或者如何做得更好?

How can define in MyController one layout and use return View::make (I think that this is right way) or how can do it better?

推荐答案

要在控制器中使用布局,必须指定:

To use layouts in controllers, you must specify:

public $layout = 'layouts.default';

您也不能返回该方法,因为它将覆盖$ layout的使用.相反,您可以使用以下内容将内容嵌入版式中:

You can also not return in the method as it will override the use of $layout. Instead, to embed your content within the layout you use:

$this->layout->nest('content', 'entries.index', array('entries' => $entries));

现在无需在您的方法中返回任何内容.这将解决它.

No need to return anything in your method now. This will fix it.

美丽的方式?"

$this->layout->nest('content', 'entries.index')->with('entries', $entries);


$this->layout->content = View::make('entries.index')->with('entries', $entries);


$this->layout->entries = $entries;
$this->layout->nest('content', 'entries.index');

这篇关于Laravel很好地定义了控制器的默认布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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