靜態化是提升網站效能、降低伺服器負載的經典策略。本文基於 Smarty 模板引擎,展示一套完整的靜態頁面生成方案,涵蓋首頁、列表頁、內容頁的差異化靜態化邏輯,並解決目錄自動建立、模板賦值、檔案寫入等關鍵技術點,適合中小型 CMS 或內容型站點參考。
$smarty->fetch() 將資料填充模板,產生 HTML 字串。function staticIndex() {
global $smarty, $article;
// 1. 獲取最新 6 條文章
$newslist = $article->getArticles(null, 54, 'DESC', 1, 6, false, 1, 2, '', 0, 0, 1);
// 2. 資料預處理:截斷標題、補全字段
if ($newslist) {
foreach ($newslist as $k => $v) {
$newslist[$k]['title_all'] = $v['title']; // 完整標題
$newslist[$k]['title'] = cutstr($v['title'], 36, '…'); // 截斷標題
}
$smarty->assign('newslist', $newslist);
}
// 3. 渲染模板獲取 HTML
$content = $smarty->fetch('index.html', true);
// 4. 寫入靜態檔案
$static_name = ROOT_PATH . 'index.html';
@file_put_contents($static_name, $content); // 直接覆蓋寫入,無需 fopen
return true;
}
關鍵點說明:
fetch() 第二參數傳 true 表示返回字串而非直接輸出。file_put_contents() 替代 fopen + fwrite + fclose,程式碼更簡潔且支援原子寫入(配合 LOCK_EX)。function staticContent() {
global $smarty;
$ids = $this->getListIds(); // 獲取所有需靜態化的內容 ID 列表
foreach ($ids as $k => $value) {
// 1. 確保分類目錄存在
$cat_dir = ROOT_PATH . 'demo/' . $value['catid'] . '/';
if (!is_dir($cat_dir)) {
mkdir($cat_dir, 0755, true); // 遞迴建立,權限 0755
}
// 2. 獲取單頁渲染內容
$html_content = $this->getDemoContent($value['demoid']);
// 3. 定義靜態檔案路徑:demo/分類ID/內容ID.html
$static_name = $cat_dir . $value['demoid'] . '.html';
// 4. 寫入檔案
@file_put_contents($static_name, $html_content);
}
return true;
}
// 輔助方法:獲取所有內容 ID
function getListIds() {
$sql = "SELECT * FROM {$this->tablepre}demo ORDER BY demoid ASC";
$rs = $this->db->getAll($sql);
return $rs ?: false;
}
function getDemoContent($id) {
global $smarty, $view_templates, $admin_templates;
loadModel(['demo']);
$demo = new demo();
// 1. 設定模板目錄
$smarty->template_dir = ROOT_PATH . $view_templates;
// 2. 獲取模板詳情與內容資料
$getMobanOne = $this->getMobanDetail($id);
$mobandetail = $demo->MobanList($id);
// 3. 批量賦值
foreach ($mobandetail as $k => $v) {
$smarty->assign($k, $v);
}
// 4. 額外賦值
$this->catid = $getMobanOne['catid'];
$smarty->assign('pre_title', $mobandetail['membername']);
$smarty->assign('mobandetail', $mobandetail);
// 5. 渲染並返回
$content = $smarty->fetch('demo_show.html', true);
$smarty->template_dir = ROOT_PATH . $view_templates; // 恢復預設目錄
return $content;
}
file_put_contents、mkdir、fetch 加上異常捕獲與日誌記錄。$smarty->compile_check = false),提升渲染速度。本方案展示了基於 Smarty 的靜態化全流程:資料獲取 → 模板渲染 → 目錄管理 → 檔案落地。核心優勢在於「人工可控、按需生成」,避免了傳統動態頁面的重複查詢與渲染開銷。配合上述優化建議,可構建出高效、穩定、易維護的靜態化系統,支撐日均百萬 PV 級別的內容型站點。