如何自动加载页眉和页脚视图?

How do I automatically load a header and footer view?

我刚开始使用 CodeIgniter,但我对 mvc 结构和 CodeIgniter 本身有足够的了解,可以做一些简单的事情,比如在控制器中加载视图和自动加载库 e.c.t。但我遇到的问题是我有一个页眉和页脚视图,我希望每次加载视图文件时自动加载它。

我做了一些搜索,很多建议都过时了,或者有时我根本不理解解决方案。我制作了页眉视图并在其中链接了 CSS,还创建了页脚视图。所以假设我想加载默认的欢迎页面,如下所示:

public function index() {
      $this->load->view('welcome_message');
}

我可以像这样手动加载它们:

public function index() {
      $this->load->view('common/header');
      $this->load->view('welcome_message');
      $this->load->view('common/footer');
}

但我想要的是像正常一样加载视图,并自动加载页眉和页脚。我知道这需要使用带有某种模板函数的自定义库来完成,但我还不够了解,无法从头开始。

我这样做了并且对我有用。

MY_Loader.php

class MY_Loader extends CI_Loader{
    public function template($content,$var=array()){
        $this->view('common/header');
        $this->view($content,$var);
        $this->view('common/footer');
    }
}

放在core文件夹中。

在你的控制器中:

 public function index(){
   $content = "welcome_message";
   $data = array();
   $data['name'] = "Max";
   $data['country'] = "USA";
   $this->load->template($content,$data);
 }

调用视图中的数据:

<html>
  <?php echo $name.' - '.$country; ?>
</html>

创建一个名为 MY_Controller 的核心控制器 class 并使每个控制器都扩展该控制器:

class MY_Controller extends CI_Controller
{

    public $data = array();

    public function __construct()
    {
        parent::__construct();
    }

    public function render($view)
    {
        $this->view('layouts/header', $this->data);
        $this->view($view, $this->data);
        $this->view('layouts/footer', $this->data);
    }

}

现在在您的控制器中:

class Welcome extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $this->data['title'] = 'Welcome Home';
        $this->render('welcome_view');
    }

}