| 1 |
<?php |
| 2 |
/* |
| 3 |
* SixtyLinesTemplate.php - 60行しかないけどSmartyより速いテンプレートエンジン |
| 4 |
* |
| 5 |
* 使い方: |
| 6 |
* require_once('SixtyLinesTemplate.php'); |
| 7 |
* $TEMPLATE_DIR = 'templates'; // 省略可、パーミッションに注意 |
| 8 |
* $context = array('title'=>'Example', |
| 9 |
* 'list'=>array(10,'<A&B>',NULL)); |
| 10 |
* include_template('template.php', $context); |
| 11 |
* |
| 12 |
* ライセンス: public domain (自由に改造してね) |
| 13 |
*/ |
| 14 |
|
| 15 |
/* |
| 16 |
* テンプレートを探すディレクトリ。 |
| 17 |
*/ |
| 18 |
$TEMPLATE_DIR = ''; |
| 19 |
|
| 20 |
/* |
| 21 |
* テンプレートを読み込んで実行する。 |
| 22 |
* $_context は変数名をキー、値を要素とする連想配列。 |
| 23 |
*/ |
| 24 |
function include_template($filePath, $_context, $charset = 'UTF-8') { |
| 25 |
// originalとは違い、cache fileを作らないで直接利用する |
| 26 |
$s = file_get_contents($filePath); |
| 27 |
$s = convert_string($s); |
| 28 |
// header("Content-Type: text/html; charset=$charset"); |
| 29 |
extract($_context); |
| 30 |
eval("?>".$s); |
| 31 |
} |
| 32 |
|
| 33 |
/* |
| 34 |
* filename を読み込み、convert_string() で置換してから |
| 35 |
* filename.cache に書き込む。読み書きのロックは省略。 |
| 36 |
* (file_{get,put}_contents() はファイルロックできるようにすべきだ。) |
| 37 |
*/ |
| 38 |
function convert_template($filename) { |
| 39 |
global $TEMPLATE_DIR; |
| 40 |
if (! file_exists($filename) && $TEMPLATE_DIR) |
| 41 |
$filename = "$TEMPLATE_DIR/$filename"; |
| 42 |
$cachename = $filename . '.cache'; |
| 43 |
if (! file_exists($cachename) || filemtime($cachename) < filemtime($filename)) { |
| 44 |
$s = file_get_contents($filename); |
| 45 |
$s = convert_string($s); |
| 46 |
file_put_contents($cachename, $s); |
| 47 |
} |
| 48 |
return $cachename; |
| 49 |
} |
| 50 |
|
| 51 |
/* |
| 52 |
* テンプレートの中身を置換する。 |
| 53 |
* - '#{...}' を 'echo ...;' に置換 |
| 54 |
* - '%{...}' を 'echo htmlspecialchars(...);' に置換 |
| 55 |
* - ついでにXML宣言も置換 |
| 56 |
*/ |
| 57 |
function convert_string($s) { |
| 58 |
$s = preg_replace('/^<\?xml/', '<<?php ?>?xml', $s); |
| 59 |
$s = preg_replace('/#\{(.*?)\}/', '<?php echo $1; ?>', $s); |
| 60 |
$s = preg_replace('/%\{(.*?)\}/', '<?php echo htmlspecialchars($1); ?>', $s); |
| 61 |
return $s; |
| 62 |
} |
| 63 |
|