天天看點

Discuz!X json輸出解析後模闆

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放進相應的容器内部就可以了。

實際上正如那段話所叙述,需要打亂輸出順序進行重組的,利用輸出緩沖是很好解決的。