• 一步一步重写 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
  • 相关阅读:
    倚天
    第5課 森さんは7時に起きます。
    第1課 李さんは中国人です
    一个整体的规划
    こんにちは
    原始凭证
    第3課 ここはデパートです
    ERP术语
    第2課 これはほんです
    vc 问题总结
  • 原文地址:https://www.cnblogs.com/zhenyu-whu/p/3272065.html
Copyright © 2020-2023  润新知