Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

CodeIgniter 2.1 實作 Layout 版面與分頁功能

CodeIgniter 本身沒有 Rails 那種 layout 機制,但只要寫一支自訂 library,就能把「頁面共用框架」與「內容區」拆開,湊出接近 Rails 的開發體驗。

準備測試資料

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

這個類別抓住 CI 的執行個體,把要顯示的 view 先渲染成字串塞進 content_for_layout,再交給 layout 樣板輸出。

<?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

版面裡固定放 header、footer 與主體欄位,中間用 content_for_layout 承接各頁內容。

<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>

關於分頁

有了 Layout 之後,分頁只要交給 CI 內建的 Pagination 類別:在控制器中設定 base_url、total_rows 與 per_page,用 $this->db->limit() 搭配 offset 取當頁資料,再把產生的連結字串當成一般變數傳進 view 即可。因為版面已由 layout 統一處理,分頁列只需寫在內容樣板裡,不必每頁重複一次。

Copyright © Linux教程網 All Rights Reserved