0

我创建并传递一个数据数组:

public function home()
{


    $data['page'] = 'home';
    $data['table'] = 'pageData';
    $data['temp'] = 'temp_1';

    $this->template($data);


}


    public function template($data)
{

    $this->load->model("model_get");


    $data['results'] = $this->model_get->getData($data);

    $this->load->view('template', $data);


}

这是模板视图:

<?php

$this->load->view('header');

$this->load->view('nav', $data);

$data['results'] = $results;

$this->load->view($temp, $data);

$this->load->view('footer');

?>

它在以下位置为未定义的变量引发异常:

$this->load->view('nav', $data);

但仍会加载视图并完成其中的所有 if 语句,并从存储在$temp.

为什么会抛出异常?

4

1 回答 1

0

您尚未在该视图中填充 $data 以加载第二个视图。您的代码名称太模糊,无法真正理解它应该做什么,但让我们分解一下。

public function home()
{
$data['page'] = 'home';
$data['table'] = 'pageData';
$data['temp'] = 'temp_1';
$this->template($data);
}


public function template($data)
{
$this->load->model("model_get");
$data['results'] = $this->model_get->getData($data);
//I assume getData takes a table name and returns all the data
//This only works because you're taking all the data passed from the first function
//in the function above.
$this->load->view('template', $data);
}


<?php
$this->load->view('header');
$this->load->view('nav', $data);
//At this point $data is empty. You have available $results, $page, $table and $temp
//because they were passed from the template function above.
$this->load->view('nav', $results);
//The line above is what it appears you need, rather than $data.
$data['results'] = $results;
//You've repopulated $data here but now all it contains is $results.
$this->load->view($temp, $data);
$this->load->view('footer');
?>

您误解的是 $data 不是持久的,当您通过加载带有 $data 作为第二个参数的视图将其传递给视图时,它会分解为其组件,因此 $data 本身不再可用。

于 2012-12-09T11:55:31.607 回答