Discuz!X json输出解析后模板

来源:互联网 发布:守望先锋生涯数据出错 编辑:程序博客网 时间:2024/06/06 08:25

Discuz的模板机制可以很方便的用HTML写出前端模板,然后将模板直接输出到浏览器。
一般情况是,解析的模板是整个页面的。直接将需要更新的页面部分输出即可,不过有些时候可能要一个json传送多组数据。这样直接输出就不行了。再手写一个输出到字符串的template显然也比较麻烦。
实际利用输出缓冲就可以达到相应的目的。下面是一段关于php的输出缓冲(output buffering)的描述,因此利用输出缓冲就能够达到需要的效果。

Without output buffering, PHP sends data to your web server as soon as it is ready - this might be line by line or code block by code block. Not only is this slow because of the need to send lots of little bits of data, but it also means you are restricted in the order you can send data. Output buffering cures these ills by enabling you to store up your output and send to send it when you are ready to - or to not send it at all, if you so decide.

整体来说,输出缓冲将本该输出到浏览器的内容拦截在了当前脚本的内存缓冲区中。所以使用输出缓冲后,需要从缓冲区中提取(ob_get_contents)。ob_get_clean相当于执行ob_get_contents后再执行ob_clean
示例如下:

    ob_start();    //开始使用output buffering    ob_clean();    //清空之前的output buffering    include template('replay_tool:replayblock');     //调用discuz!X的模板解析函数    $html = ob_get_clean();    //从output buffering取出模板内容    echo json_encode(array(                                'total' => $totalcnt,                                'maxpage' => $maxpage,                                'html' => $html,                            ));    //输出json

这样在主页面模板里用js取出html放进相应的容器内部就可以了。
实际上正如那段话所叙述,需要打乱输出顺序进行重组的,利用输出缓冲是很好解决的。

原创粉丝点击