新建測試用數據和數據表。表結構如下:
- SET FOREIGN_KEY_CHECKS=0;
-
- -- ----------------------------
- -- Table structure for `posts`
- -- ----------------------------
- DROP TABLE IF EXISTS `posts`;
- CREATE TABLE `posts` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `title` varchar(50) NOT NULL,
- `content` text NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
-
- -- ----------------------------
- -- Records of posts
- -- ----------------------------
- INSERT INTO `posts` VALUES ('1', 'aa', 'aaaaaaa');
- INSERT INTO `posts` VALUES ('2', 'bb', 'bbbbbb');
- INSERT INTO `posts` VALUES ('3', 'cc', 'cccccccc');
- INSERT INTO `posts` VALUES ('4', 'dd', 'dddddd');
application/libraries下新建Layout.php:
- <?php
- if (!defined('BASEPATH')) exit('No direct script access allowed');
-
- class Layout
- {
- var $obj;
- var $layout;
-
- function Layout($params = array())
- {
- $this->obj =& get_instance();
- if (count($params) > 0)
- {
- $this->initialize($params);
- }
- else
- {
- $this->layout = 'layout';
- }
- }
-
- function initialize($params = array())
- {
- if (count($params) > 0)
- {
- foreach ($params as $key => $val)
- {
- $this->$key = $val;
- }
- }
- }
-
- function view($view, $data = null, $return = false)
- {
- $data['content_for_layout'] = $this->obj->load->view($view, $data, true);
-
- if($return)
- {
- $output = $this->obj->load->view($this->layout, $data, true);
- return $output;
- }
- else
- {
- $this->obj->load->view($this->layout, $data, false);
- }
- }
- }
- ?>
application/views下新建layout.php:
- <html>
- <head>
- <title><?php echo $title_for_layout; ?></title>
- <meta http-equiv="content-type" content="text/html;charset=utf-8" />
- <link rel="stylesheet" href="<?php echo base_url(); ?>/assets/css/style.css" type="text/css" />
- </head>
- <body>
- <div id="pagewidth">
- <div id="header"><img src="<?php echo base_url(); ?>/assets/img/header.gif" width="728" height="90"></div>
- <div id="wrapper" class="clearfix">
- <div id="twocols" class="clearfix">
- <?php echo $content_for_layout; ?>
- </div>
- </div>
- <div id="footer"><img src="<?php echo base_url(); ?>/assets/img/footer.gif" width="728" height="90"></div>
- </div>
- </body>
- </html>