php - Laravel 以一种很好的方式从 Controller 定义默认布局

标签 php laravel

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

当我在 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/

相关文章:

php - 添加特殊字符时出现 MySQL 错误,特别是符号,即使使用 mysql_real_escape_string() 方法

mysql - Laravel - 如何将包含串联查询的派生表转换为 Eloquent 语法?

mysql - Laravel 的导入器映射问题

php - PostgreSQL 迁移失败,错误消息为 'Could not find driver'

php - Laravel 中的@yield、@section

php - 使用 JQuery 和 Bootstrap 切换按钮 - 如何在切换后更改非事件类

php - 跨度为 float 的内联 block ,依赖于看似无关的代码

laravel - 我应该怎么做按Elasticsearch使用elasticquent搜索结果页

php - Excel工作表导入数据库时​​如何转换日期?

php - 团队算法之间的调度匹配