在 ThinkPHP 專案中啟用 'SHOW_RUN_TIME' => true 後,模板中使用 {__RUNTIME__} 標籤有時無法正常輸出頁面運行時間。
查看 ThinkPHP/Lib/Think/Core/View.class.php 中 output() 方法原始碼:
if (C('HTML_CACHE_ON')) HtmlCache::writeHTMLCache($content);
if ($display) {
if (false !== strpos($content, '{__RUNTIME__}')) {
$runtime = C('SHOW_RUN_TIME') ? ''.$this->showTime().'' : '';
$content = str_replace('{__RUNTIME__}', $runtime, $content);
}
echo $content;
// ...
}
問題:僅當模板內容包含 {__RUNTIME__} 時才替換並輸出運行時間。若模板未包含此標籤(或被緩存替換),運行時間將完全不顯示。
修改 View.class.php 中的 output() 方法,確保無論模板是否包含標籤,運行時間都會輸出:
if (C('HTML_CACHE_ON')) HtmlCache::writeHTMLCache($content);
if ($display) {
$runtime = C('SHOW_RUN_TIME') ? ''.$this->showTime().'' : '';
if (false !== strpos($content, '{__RUNTIME__}')) {
$content = str_replace('{__RUNTIME__}', $runtime, $content);
} else {
$content .= $runtime; // 關鍵修復:無標籤時追加到頁面末尾
}
echo $content;
if (C('SHOW_PAGE_TRACE')) $this->showTrace();
return null;
} else {
return $content;
}
$runtime{__RUNTIME__},執行替換(原有行為)$content .= $runtimeView.class.php 並保存Runtime/Cache/ 目錄)SHOW_RUN_TIME,避免洩露效能資訊SHOW_PAGE_TRACE 可獲得更詳細的執行追蹤{__RUNTIME__}更多 ThinkPHP 相關技巧,請參考本站專題:《ThinkPHP 入門教程》及《ThinkPHP 常用方法總結》。