如何在同一个控制器中使用多个布局?

时间:2013-08-12 10:53:41

标签: laravel laravel-4

我想问一下如何在Laravel中为同一个控制器定义多个布局。 这里的场景如下:

我有一个控制器Home,我在这个控制器中有两个动作,一个叫做steps,另一个叫做登录。

我希望他们两个加载不同的布局。

我以前的做法如下:

protected $layout = "layouts.page";

public function index()
{
    // Get to the page of the website making steps
    $this->layout->content = View::make('steps');
}

我可以定义多个布局吗?也许传递数组如下:

protected $layout = array('first' => "layouts.page", 'second' => 'layouts.second');

6 个答案:

答案 0 :(得分:3)

最佳解决方案是创建一种方法来生成视图,嵌套多个布局:

return View::make('layouts.master', array())
       ->nest('section_one', YOUR_SECOND_MASTER, array())
       ->nest...

并停止使用布局设置protected $layout

答案 1 :(得分:3)

我以这种方式实现

$this->layout = View::make('layout.master');
$this->layout->content = View::make('step.demo')

答案 2 :(得分:2)

使用View Composers或查看将子视图传递给http://laravel.com/docs/responses#views下的视图的部分。

您还可以为http://laravel.com/docs/templates#blade-templating

中定义的布局指定多个部分

编辑:

如果要为同一控制器中的不同视图定义主布局,请在“查看自己”上定义布局。请查看Using A Blade Layout

部分

@extends用于定义视图本身的布局。

希望这有助于您所寻找的目标。

答案 3 :(得分:1)

如果您查看控制器可能扩展的BaseController,您将看到布局变量最终仅用作任何旧视图的结果。

换句话说,您的$layout变量只是一个视图。您可以在控制器中创建任何$layout变量:

<?php

class MyController extends BaseController {

    protected $layout;

    protected $layout_alt;

    // Here we're over-riding setupLayout() from
    // the BaseController
    protected function setupLayout()
    {
        if ( ! is_null($this->layout))
        {
            $this->layout = View::make($this->layout);
        }

        if ( ! is_null($this->layout_alt))
        {
            $this->layout_alt = View::make($this->layout_alt);
        }

    }

}

然后在您看来,您可以返回:

 $this->layout_alt->content = View::make('steps');

当然,正如Abishek R Srikaanth指出的那样,可能性是无穷无尽的。你也可以用Blade做一些奇特的东西:D

答案 4 :(得分:1)

我这样做的方式与@ fideloper的答案非常相似。

protected $layout;
private $_layout = null;

public function __construct()
{

}

private function _setupLayout()
{
    if ( ! is_null($this->_layout))
    {
        $this->layout = View::make($this->_layout);
    }
}

public function home() {
    $this->_layout = 'layouts.1col_public';
    $this->_setUpLayout();
    $this->layout->content = View::make('static/home');
}

public function about() {
    $this->_layout = 'layouts.2col_public';
    $this->_setUpLayout();
    $this->layout->active_menu = 'about';
    $this->layout->content = View::make('static/default');
}

答案 5 :(得分:0)

这不常见,我还没有测试过,但值得一试。

在控制器的方法中:

$this->layout = View::make('layouts.master1");