6

我在使用直接 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

意见/主页/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'));但这否定了我必须将所有变量发送到数组的观点。这不可能是唯一的方法。

视图模板文档似乎没有涉及使用来自控制器的嵌套视图执行变量。

4

3 回答 3

5

您可以通过这种方式传递变量;

class Home_Controller extends Base_Controller {

    public $layout = 'layouts.default';

    public function action_index()
    {

        $this->layout->nest('content', 'home.index')
                ->with('name', 'James');
    }

}
于 2012-12-23T10:56:42.463 回答
3

这是我如何使用 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>

希望能帮助你弄清楚一些事情

于 2013-01-12T19:42:11.503 回答
3

我知道这个问题已经有一段时间了,但是自从被问到之后,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 文档:

http://laravel.com/docs/responses

于 2013-11-07T04:20:05.527 回答