|
发表于 2015-7-7 11:25:06
|
显示全部楼层
本帖最后由 aneasystone 于 2015-7-7 11:29 编辑
我是这样实现的,仅供参考。
1. 首先在application/views目录下新建一个目录layout,并将公用部分放到layout目录下。这里以CodeIgniter自带的Welcome页面作为示例,共建三个文件:
1.1 header.php
PHP复制代码
<h1>Welcome to CodeIgniter!</h1>
复制代码
1.2 footer.php
PHP复制代码
<p class="footer"> Page rendered in <strong>{elapsed_time}</strong> seconds.
<?php echo (ENVIRONMENT === 'development') ? 'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?>
</p>
复制代码
1.3 index.php
PHP复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $title ?></title>
</head>
<body>
<div id="container">
<?php if ($header) echo $header; ?>
<?php if ($body) echo $body; ?>
<?php if ($footer) echo $footer; ?>
</div>
</body>
</html>
复制代码
2. 然后在application/core目录下新建一个文件MY_Controller.php,如下:
PHP复制代码
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
var $template = array();
var $data = array();
public function layout ($body) {
$this->template['header'] = $this->load->view('layout/header', $this->data, true);
$this->template['body'] = $this->load->view($body, $this->data, true);
$this->template['footer'] = $this->load->view('layout/footer', $this->data, true);
$this->load->view('layout/index', $this->template);
}
}
复制代码
3. 这样就可以让我们的Controller继承MY_Controller,然后调用$this->layout('template')来显示自定义模板了。如下:
PHP复制代码
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Layout extends MY_Controller {
public function home ()
{
$this->data['title'] = 'Home Page';
$this->layout('home');
}
public function lists ()
{
$this->data['title'] = 'List Page';
$this->layout('list');
}
public function detail ()
{
$this->data['title'] = 'Detail Page';
$this->layout('detail');
}
}
复制代码
4. 最后我们在application/views目录下,把我们需要的view补上。
4.1 home.php
PHP复制代码
<div id="body">
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you'll find it located at:</p>
<code>application/views/welcome_message.php</code>
<p>The corresponding controller for this page is found at:</p>
<code>application/controllers/Welcome.php</code>
<p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p>
</div>
复制代码
4.2 list.php
PHP复制代码
<div id ="body">
<p >The is list page with same layout !</p >
</div >
复制代码
4.3 detail.php
PHP复制代码
<div id="body">
<p>The is detail page with same layout!</p>
</div>
复制代码
整个目录结构如下:
application/
+-- controllers/
+---- Layout.php
+-- core/
+---- MY_Controller.php
+-- views/
+---- layout/
+-------- header.php
+-------- footer.php
+-------- index.php
+---- home.php
+---- list.php
+---- detail.php
|
|