Smarty fetch() 回傳渲染後的 HTML 字串,配合 file_put_contents() 寫入檔案,即可實現靜態化。
function buildIndexHtml() {
global $smarty, $articleModel;
// 1. 準備資料
$news = $articleModel->getLatest(6);
foreach ($news as &$n) {
$n['short_title'] = mb_strimwidth($n['title'], 0, 36, '…');
}
$smarty->assign('newslist', $news);
// 2. 取得渲染結果
$html = $smarty->fetch('index.tpl'); // 不輸出,回傳字串
// 3. 寫入檔案
$file = ROOT_PATH . 'index.html';
@file_put_contents($file, $html);
return true;
}
function buildCategoryPages() {
global $smarty, $catModel;
$categories = $catModel->getAll();
foreach ($categories as $cat) {
$articles = $articleModel->getByCat($cat['id'], 20);
$smarty->assign('articles', $articles);
$smarty->assign('cat', $cat);
$html = $smarty->fetch('category.tpl');
$dir = ROOT_PATH . 'category/' . $cat['id'] . '/';
if (!is_dir($dir)) mkdir($dir, 0755, true);
@file_put_contents($dir . 'index.html', $html);
}
}
function buildArticleHtml($id) {
global $smarty, $articleModel;
$article = $articleModel->get($id);
if (!$article) return false;
$smarty->assign('article', $article);
$html = $smarty->fetch('article.tpl');
$dir = ROOT_PATH . 'article/' . ceil($id / 1000) . '/'; // 分目錄避免單目錄檔案過多
if (!is_dir($dir)) mkdir($dir, 0755, true);
@file_put_contents($dir . $id . '.html', $html);
return true;
}
ob_start() / ob_get_clean() 捕獲輸出,支援非 Smarty 模板。try_files 先嘗試靜態檔,不存在再落回 PHP 動態渲染:location / {
try_files $uri $uri/ /index.php?$query_string;
}