一步一步重寫 CodeIgniter 框架 (8) —— 視圖的嵌套輸出與返回


視圖函數在控制器中通過 $this->load-view() 來調用,從而輸出 html,有時候為了調試或附加處理的需要,我們需要打印出這些輸出,而不是直接通過瀏覽器輸出,這在 php 中是通過緩沖區來實現的,詳細的函數參考 http://www.php.net/manual/zh/ref.outcontrol.php

所以我們在 _ci_load 函數中可以看到

ob_start();

        include($_ci_path);

        // 如果需要返回數據,則從緩沖區中返回數據
        if ($_ci_return === TRUE) {
            $buffer = ob_get_contents();
            @ob_end_clean();
            return $buffer;
        }

        // 如果是嵌套的視圖中的輸出,則直接 flush, 以便外層視圖可以得到 buffer 中的內容,
        // 而最外層的 buffer 則導出到 output 類中進行最后的處理
        if (ob_get_level() > $this->_ci_ob_level + 1) {
            ob_end_flush();
        } else {
            $_ci_CI->output->append_output(ob_get_contents());
            @ob_end_clean();
        }

1)在 include 視圖文件之前,開啟緩沖區 ob_start(),那么視圖文件的內容就全部輸出到緩沖區,而不是通過瀏覽器輸出

2) 如果調用時參數 _ci_return 為 True, 則說明這個視圖文件的內容直接返回即可,不需要加入到最終的瀏覽器輸出中,所以調用 ob_get_contents 函數獲得返回值,並清理緩沖區 ob_end_clean()

3)注意 CI 中的 output 類是執行完所有的 view 視圖加載后,對最終內容進行處理的,所以但凡是超出第一層 buffer 的內容,全部加入緩沖區,直到第一層的視圖完畢, 通過 append_output 函數教給 Output 類來處理

加入以上代碼后,相比之前,可以對視圖進行任意層次的嵌套了~

 

為了測試結果,我們在 test_view 中嵌套另一個視圖 test_inner_view

<?php

echo 'I am the inner people of zzy, lc & lyq';

而 原先的 test_view 則更改為

<html>
<head>
<title>My First View</title>
</head>
<body>
 <h1>Welcome, we finally met by MVC, my name is Zhangzhenyu!</h1>
 <p><?php echo $info ?></p>
 <div style="border: 1px solid #ccc;">
     <?php $this->load->view('test_inner_view') ?>
 </div>
</body>
</html>

訪問 http://localhost/learn-ci/index.php/welcome/hello

可以看到輸出如下 

Welcome, we finally met by MVC, my name is Zhangzhenyu!

People you want in our model is Zhangzhenyu

I am the inner people of zzy, lc & lyq

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM