简体   繁体   English

将 model 中的值传递给 Kohana 3 中的视图

[英]Passing a value from a model to a view in Kohana 3

I have a model that fetches from my database a list that I want to be able to show in my view.我有一个 model 从我的数据库中获取我希望能够在我的视图中显示的列表。

The model looks like this: model 看起来像这样:

Class Model_services extends Model
{
    public function get_services_list() {
    $result = DB::select('*')->from('services')
            ->execute()
            ->as_array();
            return $result;
    }
}

My controller looks something like this:我的 controller 看起来像这样:

public function action_index()
{
    $this->template->title    = "services";
    $this->template->header   = View::factory('header'); 
    $services                 = Model::factory('services');
    $this->template->content  = View::factory('services')
                                      ->bind('result',$result)
    $this->template->footer   = View::factory('footer');         
 }

How do I render at the view the variables from the model?如何在视图中呈现来自 model 的变量?

You haven't actually called the model method or passed the variable from your controller class to the view.您实际上并未调用 model 方法或将变量从 controller class 传递到视图。

Change this:改变这个:

$services = Model::factory('services');
$this->template->content = View::factory('services')
                                  ->bind('result',$result);

To this:对此:

$services = Model::factory('services')->get_services_list();
$this->template->content = View::factory('services')
                                  ->bind('result', $services);

The changes here are:这里的变化是:

  • calling the method used to extract the relevant rows from the database.调用用于从数据库中提取相关行的方法。
  • using the $services variable and binding it to $result which you'll be using in the view.使用$services变量并将其绑定到您将在视图中使用的$result

In your view you'll then be able to extract the values when you reference the $result variable.在您看来,当您引用$result变量时,您将能够提取这些值。

To see what you've got from the model, test this in your view:要查看您从 model 获得了什么,请在您的视图中进行测试:

echo Debug::vars($result);

In services.php use code as below;)services.php使用代码如下;)

foreach($result as $item) {
    echo Debug::vars($item);
    // print_r($item); //alternatively you can try this also, if Debug::vars() causes pain
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM