php4 による最小限のWebページ生成エンジンはこんなかんじかな。エラー処理とかまったくないけど、自分しか実行しないからそれでよし。
テンプレートの評価は全て eval_file() 内で行われるので、グローバル変数へのアクセスは $GLOBALS か、global宣言を使わないといけない。また、php5では file_put_contents は定義されているので省略できる。
build を再帰的に実行するように変更すれば、サイトを階層構造にできる。
ディレクトリ構成
. /build //Webページ生成スクリプト /tmpl //テンプレート入れる場所 /pages //テンプレート /*.tmpl //ページのテンプレート /modules //共通モジュールテンプレート /head.tmpl //<head>〜</head>用 /header.tmpl //ページのヘッダ /footer.tmpl //ページのフッタ /exports //静的ページの出力場所
build - Webページ生成スクリプト
#!/usr/bin/php
<?
function file_put_contents($file,$content)
{
$h=fopen($file,'wb');
fwrite($h, $content);
fclose($h);
}
// evaluate $file and get content from it
function eval_file($file)
{
ob_start();
include($file);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
// configurations
$tmpl_dir='./tmpl/';
$page_dir=$tmpl_dir.'pages/';
$module_dir=$tmpl_dir.'modules/';
$export_dir='./exports/';
// build the web site
$dh=opendir($page_dir);
while($file=readdir($dh)) {
$tmpl_file=$page_dir.$file;
$pathinfo=pathinfo($tmpl_file);
$export_file=$export_dir.$file;
if ($pathinfo['extension']=='html') {
$contents=eval_file($tmpl_file);
file_put_contents($export_file,$contents);
echo $export_file."\n";
}
}
closedir($dh);
?>
tmpl/pages/*.html - ページのテンプレート(例えば、index.html)
<? global $module_dir ?> <html> <head> <? include($module_dir.'head.tmpl'); ?> <title>ページのタイトル</title> </head> <body> <? include($module_dir.'header.tmpl') ?> <div id="content"> ページの内容 </div> <? include($module_dir.'footer.tmpl') ?> </body> </html>
tmpl/modules/head.tmpl - 共通の<head>〜</head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="/css/site.css"> <script type="text/javascript" src="/js/site.js"></script>
生成されたページ
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="/css/site.css"> <script type="text/javascript" src="/js/site.js"></script> <title>ページのタイトル</title> </head> <body> <div id="header">共通ヘッダ</div> <div id="content"> ページの内容 </div> <div id="footer">共通フッタ</div> </body> </html>
{header,footer}.tmpl は省略。site.css とか site.js とかは別途用意。
groundwalker.com