0

我的问题是 Kohana 只渲染视图。当我

View::factory('/foo/bar')在 Controller_Other 中,它不会首先击中 Controller_Foo。我希望它击中控制器,然后渲染视图。

class Controller_Other extends Controller_Template {
    public $template = 'main';
    public function action_index() {
        $this->template->body = View::factory('/foo/bar');
    }
}

我如何让它首先通过控制器运行:

class Controller_Foo extends Controller_Template {
    public function action_bar() {
        $this->myVar = 'foo';
    }
}

所以在视图中,当我从其他人调用它时$myVar总是设置?views/foo/bar.phpView::factory()

编辑:

必须有一种更清洁的方法,而不是强制action_bar将其自己的视图呈现为字符串然后继续:

$foo = new Controller_Foo($this->request, $this->response);
$this->template->body = $foo->action_bar();
4

2 回答 2

2

我不确定您在做什么 - 想要绑定全局视图变量或执行内部请求。无论如何,以下是这两种情况的示例:

绑定全局视图变量

class Controller_Other extends Controller_Template {
    public $template = 'main';

    public function action_index() {
      View::bind_global('myVar', 'foo'); 
      //binds value by reference, this value will be available in all views. Also you can use View::set_global();

      $this->template->body = View::factory('/foo/bar');
    }

}

做一个内部请求

这是 'foo/bar' 动作

class Controller_Foo extends Controller_Template {

     public function action_bar() {
        $myVar = 'foo';
        $this->template->body = View::factory('/foo/bar', array('myVar' => $myVar);
     }
}



class Controller_Other extends Controller_Template {
    public $template = 'main';
    public function action_index() {
         $this->template->body = Request::factory('foo/bar')->execute()->body();
         //by doing this you have called 'foo/bar' action and put all its output to curent requests template body
    }
}
于 2012-05-04T12:46:25.257 回答
0

在渲染之前,您应该始终将 $myVar 变量传递给查看

public function action_index() {
    $this->template->body = View::factory('/foo/bar')->set('myVar', 'foo');
}

在其他控制器中,您应该再次设置它,因为 View 只是一个模板。如果您打算在脚本的不同位置使用相同的视图,您可以将 View 实例分配给某个变量并在以下位置使用它:

public function action_index() {
    $this->view = View::factory('/foo/bar')->set('myVar', 'foo');

    $this->template->body = $this->view ;
}

public function action_bar() {
    $this->template->head = $this->view ;
}
于 2012-05-04T08:14:20.263 回答