用Smarty模板生成html文件,其实就是在 display() 的同时,增加了 ob_start()、b_get_contents() 和 fwrite() 函数。
具体实现方法,请看下面两个文件:
文件一: generate_html.php
<?php
require_once('inc/smarty.inc.php');
require_once('include/config.php');
ob_start();
$title = "title";
$description = "description";
$keywords = "keywords";
$outfilename = "test.html";
$smarty->assign("TITLE", $title);
$smarty->assign("DESCRIPTION", $description);
$smarty->assign("KEYWORDS", $keywords);
$smarty->assign("CSSPATH", "/css");
$smarty->assign("TPL_LEFT", TPL_LEFT);
$smarty->assign("TPL_RIGHT", TPL_RIGHT);
$smarty->assign("TPL_TOP", TPL_TOP);
$smarty->assign("TPL_FOOTER", TPL_FOOTER);
$smarty->assign("TPL_CENTER", TPL_CATEGORY);
$smarty->display(TPL_MAIN); // TPL_MAIN 等常量在 include/config.php 中已经被定义
$str = ob_get_contents();
$fp = @fopen($outfilename, 'w');
if (!$fp) {
Show_Error_Message( ERROR_WRITE_FILE );
}
fwrite($fp, $str);
fclose($fp);
ob_end_clean();
?> |
文件二: templates/main.htm
<html>
<head>
<{config_load file="global.conf"}>
<title><{$TITLE}></title>
<meta name="description" content="<{$DESCRIPTION}>">
<meta name="keywords" content="<{$KEYWORDS}>">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="<{$CSSPATH}>/style.css" type="text/css">
</HEAD>
<body>
<table width="<{#TABLE_WIDTH#}>" border="0" cellspacing="0" cellpadding="0" align="center">
<tr>
<td colspan="3">
<{include file="$TPL_TOP"}>
</td>
</tr>
<tr>
<td width="<{#TABLE_LEFT_WIDTH#}>" align="left" valign="top">
<{include file="$TPL_LEFT"}>
</td>
<td width="<{#TABLE_CENTER_WIDTH#}>" align="center" valign="top">
<{include file="$TPL_CENTER"}>
</td>
<td width="<{#TABLE_RIGHT_WIDTH#}>" align="right" valign="top">
<{include file="$TPL_RIGHT"}>
</td>
</tr>
<tr>
<td colspan="3">
<{include file="$TPL_FOOTER"}>
</td>
</tr>
</table>
</body>
</html>
|