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

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


我做了一些搜索,很多建议都过时了,或者有时我根本不明白解决方案。我已经创建了我的页眉视图并在其中链接了我的 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');

}

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


倚天杖
浏览 155回答 2
2回答

holdtom

我这样做了,它对我有用。MY_Loader.phpclass MY_Loader extends CI_Loader{&nbsp; &nbsp; public function template($content,$var=array()){&nbsp; &nbsp; &nbsp; &nbsp; $this->view('common/header');&nbsp; &nbsp; &nbsp; &nbsp; $this->view($content,$var);&nbsp; &nbsp; &nbsp; &nbsp; $this->view('common/footer');&nbsp; &nbsp; }}放在core文件夹里。在您的控制器中:&nbsp;public function index(){&nbsp; &nbsp;$content = "welcome_message";&nbsp; &nbsp;$data = array();&nbsp; &nbsp;$data['name'] = "Max";&nbsp; &nbsp;$data['country'] = "USA";&nbsp; &nbsp;$this->load->template($content,$data);&nbsp;}调用视图中的数据:<html>&nbsp; <?php echo $name.' - '.$country; ?></html>

心有法竹

创建一个名为的核心控制器类MY_Controller并使每个控制器都扩展此控制器:class MY_Controller extends CI_Controller{&nbsp; &nbsp; public $data = array();&nbsp; &nbsp; public function __construct()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; parent::__construct();&nbsp; &nbsp; }&nbsp; &nbsp; public function render($view)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->view('layouts/header', $this->data);&nbsp; &nbsp; &nbsp; &nbsp; $this->view($view, $this->data);&nbsp; &nbsp; &nbsp; &nbsp; $this->view('layouts/footer', $this->data);&nbsp; &nbsp; }}现在在您的控制器中:class Welcome extends MY_Controller{&nbsp; &nbsp; public function __construct()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; parent::__construct();&nbsp; &nbsp; }&nbsp; &nbsp; public function index()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->data['title'] = 'Welcome Home';&nbsp; &nbsp; &nbsp; &nbsp; $this->render('welcome_view');&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP