PHP Smarty

Smarty

PHPのテンプレートエンジンとして有名なものにSmarty(http://smarty.php.net/)があります。Mac OS X 10.3.9 で使ってみました。

まずはサイトからダウンロード
http://smarty.php.net/download.php

次の手順で sample.smarty ディレクトリの下にセットアップしました。

mkdir sample.smarty
mkdir sample.smarty/htdocs
mkdir sample.smarty/lib
mkdir sample.smarty/lib/Smarty
tar xzf ~/Smarty-2.6.18.tar.gz
mv Smarty-2.6.18/libs/* sample.smarty/lib/Smarty/
rm -fr Smarty-2.6.18/
mkdir sample.smarty/etc
mkdir sample.smarty/etc/templates
mkdir sample.smarty/etc/templates_c
mkdir sample.smarty/etc/cache
mkdir sample.smarty/etc/configs

PHPファイル(sample.smarty/htdocs/index.php)は次のようになります。
<?php
require(‘../lib/Smarty/Smarty.class.php’);
$smarty = new Smarty();

$smarty->template_dir = ‘../etc/templates’;
$smarty->compile_dir = ‘../etc/templates_c’;
$smarty->cache_dir = ‘../etc/cache’;
$smarty->config_dir = ‘../etc/configs’;

$smarty->assign(‘name’, ‘hiro345’);
$smarty->display(‘index.tpl’);

?>

テンプレートファイル(smarty.sample/etc/templates/index.tpl)を用意します。

<html>
<head>
<title>Smarty</title>
</head>
<body>
Hello, {$name}!
</body>
</html>

カレントディレクトリをsample.smarty/htdocsとして実行すると、次のようになります。
———
$ php -f index.php 
<html>
<head>
<title>Smarty</title>
</head>
<body>
Hello, hiro345
</body>
</html>

簡単ですね。ディレクトリの指定が相対ディレクトリなので、実際のWebアプリケーションを開発するときには、絶対ディレクトリにする必要がありそうです。コマンドラインだけで確認してみたわけですが、本格的に使うには、GETパラメータやPOSTパラメータが必要なので、きちんとApacheなども準備しなければならなそうです。

同じカテゴリの記事: Mac
同じカテゴリの記事: Program