我可以更有效地使用直接的 php 设置视图逻辑。 Blade 很酷,但不适合我。我正在尝试将所有特定于 Blade 的示例和文档转换为 PHP。我不喜欢这样的事实:我需要在 View::make() 数组中为视图分配所有变量。到目前为止我确实找到了所有这些。
控制器/home.php:
class Home_Controller extends Base_Controller {
public $layout = 'layouts.default';
public function action_index()
{
$this->layout->name = 'James';
$this->layout->nest('content', 'home.index');
}
}
视图/布局/default.php:
// head code
<?php echo Section::yield('content') ?>
// footer code
views/home/index.php
<?php Section::start('content'); ?>
<?php echo $name ?>
<?php Section::stop(); ?>
我遇到了这个错误:
Error rendering view: [home.index] Undefined variable: name
。我知道 $this->layout->nest('content', 'home.index', array('name' => 'James'));
有效,但这否定了我关于必须将所有变量发送到数组的观点。这不是唯一的方法。
视图模板文档似乎没有涉及使用控制器中的嵌套视图来处理变量。
你可以通过这种方式传递变量;
class Home_Controller extends Base_Controller {
public $layout = 'layouts.default';
public function action_index()
{
$this->layout->nest('content', 'home.index')
->with('name', 'James');
}
}
这是我如何使用 Laravel 进行模板化的示例。
Class Products_Controller extends Whatever_Controller {
public $layout = 'layouts.main';
public function get_index()
{
// .. snip ..
$view = View::make('home.product')
->with('product', $product); // passing all of my variable to the view
$this->layout->page_title = $cat_title . $product->title;
$this->layout->meta_desc = $product->description;
$this->layout->content = $view->render(); // notice the render()
}
}
我的主要布局看起来像
<html>
<head>
<title> {{ $page_title }} </title>
<meta name="description" content="{{ $meta_desc }}" />
</head>
<body>
{{ $content }}
</body>
</html>
主页/产品页面看起来像
<div class="whatev">
<h1> {{ $product->title }} </h1>
<p> {{ $product->description }} </p>
</div>
希望能帮助你理清一些事情
我知道这个问题已经有一段时间了,但自从提出这个问题以来,Laravel 4 已经问世了,并且有更新的方法可以做事。
如果您最近正在阅读本文,您应该考虑使用 View Composers 为您的视图准备数据。
示例:
class MyViewComposer {
public function compose($view){
$view->title = 'this is my title';
$view->name = 'joe';
...
$view->propertyX = ...;
}
}
设置视图编辑器后,将其注册到应用程序:
View::composer('home.index', 'MyViewComposer');
有关更多信息,请查看有关视图作曲家的 laravel 文档: