利用 Smarty 內建 fetch() 取得渲染後 HTML,寫入靜態檔案,實現人工觸發的靜態化發布流程,避免每次請求都執行 PHP。
<?php
// 靜態化首頁
function staticIndex() {
global $smarty, $article;
$newslist = $article->getArticles(null, 54, 'DESC', 1, 6, false, 1, 2, '', 0, 0, 1);
if ($newslist) {
foreach ($newslist as $k => $v) {
$newslist[$k]['title_all'] = $v['title'];
$newslist[$k]['title'] = cutstr($v['title'], 36, '...');
}
$smarty->assign('newslist', $newslist);
}
$content = $smarty->fetch('index.html', true); // true = 返回字串而非輸出
$staticFile = ROOT_PATH . 'index.html';
file_put_contents($staticFile, $content);
return true;
}
// 靜態化列表頁(按分類)
function staticContent() {
global $smarty;
$ids = $this->getListIds(); // 取得所有內容 ID 與分類
foreach ($ids as $row) {
$catDir = ROOT_PATH . 'demo/' . $row['catid'];
if (!is_dir($catDir)) mkdir($catDir, 0755, true);
$html = $this->getDemoContent($row['demoid']);
$file = $catDir . '/' . $row['demoid'] . '.html';
file_put_contents($file, $html);
}
return true;
}
// 取得單頁渲染內容
function getDemoContent($id) {
global $smarty, $view_templates;
$smarty->template_dir = ROOT_PATH . $view_templates;
$detail = $this->getMobanDetail($id);
$moban = (new demo())->MobanList($id);
foreach ($moban as $k => $v) $smarty->assign($k, $v);
$smarty->assign('pre_title', $moban['membername']);
$smarty->assign('mobandetail', $moban);
return $smarty->fetch('demo_show.html', true);
}
?>
$smarty->fetch('tpl', true) 回傳渲染結果字串,不直接輸出。file_put_contents() 簡化檔案寫入(PHP 5+)。mkdir(..., true) 遞迴建立。