1

我是 Kohana 框架的新手。

我想创建控制器并在视图中显示变量。

我的控制器 Start.php:

    <?php defined('SYSPATH') or die('No direct script access.');

class Controller_Start extends Controller_Template {

    public function action_index()
    {
        $view = View::factory('start')
                    ->set('title', array('tytul 1', 'tytul 2'));

                $this->response->body($view);
    }

}

在 APPPATH/views 中有 Start.php:

<h1><?php echo $title[0] ?></h1>

当我打开网站有错误:

View_Exception [ 0 ]: The requested view template could not be found

当我显示来自操作的数据时:

$this->response->body('test');

当我打开网站时有“测试”

我的观点有什么问题?

4

1 回答 1

0

Your controller is missing the template definition, Piotr.

What you have to do in your Controller is to define what view your controller need to use:

class Controller_Start extends Controller_Template {

    // This has to be defined
    public $template = 'start';

    public function action_index()
    {
        $this->template->set('title', array('tytul 1', 'tytul 2'));

        // No need to do this if you're extending Controller_Template
        // $this->response->body($view);
    }
}

my_view is the filename (without the .php extension) of a template file located in your /application/views folder. If it's in a subfolder, then provide it in there, e.g.:

public $template = 'subfolder/start';

Note that it has to be defined as string, as the Controller_Template::before() method will transform it to a View object. This means that you do not have to create your own $view object within the action_index(), unless you want to override the default one. Then you'd need to do something like:

class Controller_Start extends Controller_Template {

    public function action_index()
    {
        $view = View::factory('start')
                    ->set('title', array('tytul 1', 'tytul 2'));

        $this->template = $view;

        // And that's it. Controller_Template::after() will set the response
        // body for you automatically
    }
}

If you want to have full control over the template and don't want Kohana to interfere I'd suggest not extending the Controller_Template class, but rather use the plain Controller and render the view yourself, e.g.:

class Controller_Start extends Controller {

    public function action_index()
    {
        $view = View::factory('start')
                    ->set('title', array('tytul 1', 'tytul 2'));

        // Render the view and set it as the response body
        $this->response->body($view->render());
    }
}
于 2013-02-20T07:46:24.923 回答