如何在 CI 3.0.x 中动态加载多个视图


How to dynamically load multiple views in CI 3.0.x

我正在尝试在 CI 3 中动态加载多个视图。 但我遇到了一些挑战。我扩展了处理布局的CI_controller:

public function layout() {
    $this->template['page_header'] = $this->load->view('global/header', $this->data, true);
    if (is_array($this->page_content)) {
      foreach ($this->page_content as $key => $value) {
        $this->template['page_content'][$key] = $this->load->view($value, $this->data, true);
      }
    }
    else {
      $this->template['page_content'] = $this->load->view($this->page_content, $this->data, true);
    }
    $this->template['page_footer'] = $this->load->view('global/footer', $this->data, true);
    $this->load->view('global/layout', $this->template);
  }

在扩展MY_Controller的控制器中,我有:

$this->page_content = array('cards/cards3', 'cards/cards1', 'cards/cards2');
$this->layout();

在我的观点中,我有:

if (is_array($page_content)) {
   foreach ($page_content as $content) {
      echo $content;
   }
}    
else {
   echo $page_content;
}

问题是在视图上我得到了数组中的最后一项。在这种情况下,cards/cards2 .

知道为什么吗?

通了。在My_controller我没有意识到视图可以连接成一个字符串。

所以我把它改成:

$this->template['page_content'] = '';
foreach ($this->page_content as $content) {
   $this->template['page_content'] .= $this->load->view($content, $this->data, true);
}