gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:11:21 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com