Smarty に必要なディレクトリ
Smarty では tempalates, templates_c, configs, cache という4つのディレクトリが 必要です。(これらの名前は、変更することができます。)tempalates には、テンプレートファイルを置きます。templates_c は、Smarty がテンプレートファイルからコンパイルファイルを作成して置く所で、私たちは、このディレクトリを用意するだけです。configs は、設定ファイルを置く所です。設定ファイルを使用しない場合は、configs ディレクトリは必要ありません。cache は、Smarty がテンプレートファイルから生成した出力ファイルを置くところです。このディレクトリも、用意するだけです。
これらディレクトリのデフォルトパスは、次に示すように、実行中の php スクリプトが置かれた場所の直下のディレクトリになります。
- exe_smarty
- use_smarty.php
- cache
- templates
- use_smarty.tpl
- templates_c
- configs
- use_smarty.conf
Smarty サンプルとソースコード
上記ディレクトリ名とファイル名で簡単なサンプルを作りました。使い方の理解に役立ててください。
サンプル: Smarty のサンプル
このサンプルのソースコードは、次の通りです。
use_smarty.php のソースコード
// Smarty ディレクトリのサンプル
if (!@include_once('Smarty.class.php')){
@include_once('Smarty/Smarty.class.php');
}
//通常は、require_once('Smarty.class.php');だけでOKですが、
// Smarty/Smarty.class.php のサーバーにも対応しました。
$smarty = new Smarty;
$smarty->assign('name','Maihy');
$smarty->display('use_smarty.tpl');
?>
templates/use_smarty.tpl のソースコード
{config_load file="use_smarty.conf"}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>{#pageTitle#}</title>
</head>
<body>
設定ファイルから読んだ変数 var_conf は、「{#var_conf#} 」です。
<br>
こんにちは、{$name}! さん。
</body>
templates/use_smarty.conf のソースコード
var_conf = "設定ファイルの変数"
Smarty をカスタマイズする
Smarty のディレクトリを、いつも php のスクリプトのあるディレクトリに作っていては、効率がわるくなります。そこで、Smarty のクラスを拡張して自分向けにカスタマイズしましょう。
次の例では、インクルードパスの下に新しいディレクトリ"/guestbook/"を作成し、setup.php という新しいファイルを作成ました。Smarty に必要な4つのディレクトリもディレクトリ"/guestbook/"に置いたことを前提としています。デバック時は、ローカルなディレクトリを指定し、リモートと切り換えています。ディレクトリのパスは、例のようにフルパスで指定したほうがよさそうです。ディレクトリの名前は、好みで変えることができます。
setup.php のソースコード
// Smartyライブラリを読み込む
require_once('Smarty.class.php');
class Smarty_GuestBook extends Smarty {
function Smarty_GuestBook()
{
// クラスのコンストラクタ。
$this->Smarty();
if ($_SERVER['SERVER_NAME']=='localhost') {
//ローカルホスト
$this->template_dir = 'C:/xampp/htdocs/・・・・・/guestbook/templates/';
$this->compile_dir = 'C:/xampp/htdocs/・・・・・/guestbook/templates_c/';
$this->config_dir = 'C:/xampp/htdocs/・・・・・/guestbook/configs/';
$this->cache_dir = 'C:/xampp/htdocs/・・・・・/guestbook/\cache/';
} else {
//リモートホスト
$this->template_dir = '/home/・・・・・/guestbook/templates/';
$this->compile_dir = '/home/・・・・・/guestbook/templates_c/';
$this->config_dir = '/home/・・・・・/guestbook/configs/';
$this->cache_dir = '/home/・・・・・/guestbook/cache/';
}
$this->caching = false;//デバッグ時:キャッシングを有効にするときはtrue
}
}
?>
require_once('Smarty.class.php'); ではなく、次のようにつかいます。
これで、Smarty で使用する4つのディレクトリを、自分向けにカスタマイズすることができました。
setup.php を使う
$smarty = new Smarty_GuestBook;
