我一直在阅读Laravel 4文档,并且已经制作了一个演示应用程序来帮助学习。
我找不到很多关于使用刀片和控制器进行视图模板化的文档。 哪种方法是正确的还是归结为个人偏好?
E.g。 1
控制器/ HomeController.php
protected $layout = 'layouts.main';
public function showWelcome()
{
$this->layout->title = "Page Title";
$this->layout->content = View::make('welcome');
}
查看/布局/ main.blade.php
<html>
<head>
<title>{{ $title }}</title>
</head>
<body>
{{ $content }}
</body>
</html>
查看/ welcome.blade.php
<p>Welcome.</p>
E.g。 2
控制器/ HomeController.php
protected $layout = 'layouts.main';
public function showWelcome()
{
$this->layout->content = View::make('welcome');
}
查看/布局/ main.blade.php
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
@yield('content')
</body>
</html>
查看/ welcome.blade.php
@section('title', 'Welcome')
@section('content')
// content
@stop
上述最佳惯例和/或优势是什么?
答案 0 :(得分:4)
我没有在控制器中存储任何布局信息,我通过
将其存储在视图中@extends('layouts.master')
当我需要在控制器中返回视图时,我使用:
return \View::make('examples.foo')->with('foo', $bar);
我更喜欢这种方法,因为视图决定了要使用的布局而不是控制器 - 这需要重新分解。
答案 1 :(得分:1)
我不喜欢他们中的任何一个。布局可能是Laravel最奇怪的部分。控制器版本没有意义;然后控制器的所有方法都需要该视图。 @yield版本是一堆样板。我编写了“特定于方法的布局”:
public function index()
{
return View::make('layouts.main', [
'layout_data' => 'sup'
])->nest('content', 'welcome', [
'view_data' => 'sup'
]);
}
我认为应该在文档中提到这是一个选项。
答案 2 :(得分:0)
我更喜欢第二个,因为它显示了视图和控制器代码之间更清晰的分离。对我而言,标题是内容视图的属性似乎更合乎逻辑,而不是每次都将欢迎视图与欢迎标题组合在一起。
最后两者都是正确的并且可行,但第二种选择更易于维护。
答案 3 :(得分:0)
我更喜欢第一种方法,因为有些网站会从数据库中动态生成标题。使用第一种方法很容易传递标题。