我用谷歌搜索了两个小时,但没有找到答案。也许你能帮忙。
当我在 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 中替换返回部分时:
$this->layout->nest('content', 'entries.index', array(
'entries' => $entries
));
然后一切正常,但是..它看起来不干净而且我不喜欢它。在每个 View 中添加时 @layout('layouts.default')
一切都很好,但它不是 DRY。例如,在 RoR 中,我不需要在 Controller 中执行此类操作。
如何在 MyController
中定义一个布局并使用 return View::make
(我认为这是正确的方法)或者如何做得更好?
最佳答案
要在 Controller 中使用布局,您必须指定:
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');
关于php - Laravel 以一种很好的方式从 Controller 定义默认布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13501922/