一步一步重写 CodeIgniter 框架 (8) —— 视图的嵌套输出与返回

视图函数在控制器中经过 $this->load-view() 来调用,从而输出 html,有时候为了调试或附加处理的须要,咱们须要打印出这些输出,而不是直接经过浏览器输出,这在 php 中是经过缓冲区来实现的,详细的函数参考 http://www.php.net/manual/zh/ref.outcontrol.phpphp

因此咱们在 _ci_load 函数中能够看到html

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()app

3)注意 CI 中的 output 类是执行完全部的 view 视图加载后,对最终内容进行处理的,因此但凡是超出第一层 buffer 的内容,所有加入缓冲区,直到第一层的视图完毕, 经过 append_output 函数教给 Output 类来处理函数

加入以上代码后,相比以前,能够对视图进行任意层次的嵌套了~测试

 

为了测试结果,咱们在 test_view 中嵌套另外一个视图 test_inner_viewthis

<?php

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

而 原先的 test_view 则更改成spa

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

能够看到输出以下 调试

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
相关文章
相关标签/搜索