6

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

当我在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);
        }
    }
}

entry\index.blade.php 中

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

layouts\default.blade.php中:

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

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

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

然后一切正常,但是..它看起来不干净,我不喜欢它。在每个视图中添加时,一切@layout('layouts.default')都很好,但它不是 DRY。例如,在 RoR 中,我不需要在 Controller 中做这些事情。

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

4

3 回答 3

15

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

public $layout = 'layouts.default';

您也不能在该方法中返回,因为它会覆盖 $layout 的使用。相反,要将您的内容嵌入您使用的布局中:

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

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


编辑:

“美丽的方式?”

$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');
于 2012-11-21T20:59:28.683 回答
0

它应该是

public $layout = 'layouts.default';

这是链接模板 - 基础知识

现在你可以像这样返回你的布局

$view = View::make('entries.index')->with('entries', $entries);
$this->layout->content = $view->render();
于 2012-11-21T20:56:44.643 回答
-1
 class BaseController extends Controller {

/**
 * Setup the layout used by the controller.
 *
 * @return void
 */

/*Set a layout properties here, so you can globally
  call it in all of your Controllers*/
protected $layout = 'layouts.default';

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

}

类 HomeController 扩展 BaseController {

public function showHome()
{   
    /*now you can control your Layout it here */
     $this->layout->title= "Hi I am a title"; //add a dynamic title 
     $this->layout->content = View::make('home');
}

}

参考: http ://teknosains.com/i/tutorial-dynamic-layout-in-laravel-4

于 2014-01-29T17:32:13.880 回答