我用谷歌搜索了两个小时,但没有找到答案。也许你可以帮忙。
当我在 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);
}
}
}
在条目\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 中,我不需要在控制器中执行此类操作。
如何在MyController
一个布局中定义并使用return View::make
(我认为这是正确的方式)或如何做得更好?
若要在控制器中使用布局,必须指定:
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');
它应该是
public $layout = 'layouts.default';
这是链接模板 - 基础知识
现在您可以像这样返回布局
$view = View::make('entries.index')->with('entries', $entries);
$this->layout->content = $view->render();
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