Smartyの利用

http://smarty.php.net/ より適当なディレクトリにSmarty-*.*.*.tar.gzをダウンロード

tar zxvf Smarty-*.*.*.tar.gz

■展開後でてくるlibs/内にはコアとなる Smarty.class.php や Smartyライブラリ が収められているのでlibs/内を任意のディレクトリにコピーする。

■コンテンツを公開するディレクトリに以下のディレクトリを作成する。

templates/ — 作成したテンプレートを格納
templates_c/ — コンパイルされたファイルが格納される
configs/ — 各種設定ファイル作成した場合、そのファイルを格納
cache/ — キャッシュファイルが格納される

※templates_c/ と cache/ にはApacheが書き込めるパーミッションを設定する。

■基本的な利用
$name を表示する。

【/path/to/templates/template.tpl】
<html>
<body>
{$name}
</body>
</html>

【[HomeDir]/public_html/index.php】
<php?
include_once(“/path/to/Smarty.class.php”);

$smarty = new Smarty(); //Smartyオブジェクト生成
$smarty->template_dir = “/path/to/templates”; // テンプレートディレクトリを指定
$smarty->compile_dir = “/path/to/templates_c”; // コンパイルディレクトリを指定

$var = “VarName”;
$smarty->assign(“name”,$var); // Smarty変数に値をアサイン(割り当て)する

$smarty->display(“template.tpl”); // template.tplを出力
?>

ブラウザで[HomeDir]/public_html/index.phpにアクセスして
$name(VarName)が表示されればOK

※Smarty.class.phpのインクルードパスはシステム、又はphp.iniなどで設定してもOK

■Smarty.class.php の拡張
繰り返しディレクトリパスの設定や同じ変数の設定を行わないようにするため、classを継承して一箇所で管理する。又、自前のプラグインを利用するための定義を行う。

□以下のファイルを作成し、任意のディレクトリに配置する。
【/path/to/MySmarty.php】
<?php
// Smartyライブラリを読み込む
include_once(“/path/to/Smarty.class.php”);

class MySmarty extends Smarty {

function MySmarty()
{
$this->template_dir = ‘/path/to/templates’;
$this->compile_dir = ‘/path/to/templates_c’;
$this->config_dir = ‘/path/to/configs’;
$this->cache_dir = ‘/path/to/cache’;
// plugins_dir は配列なので複数定義できる。
// 自前のプラグインを置くディレクトリを最初に指定
$this->plugins_dir = array(‘/path/to/my_plugins’,’plugins’);
// 親クラスのコントラクタを呼び出す
$this->Smarty();
}

}
?>

□/path/to/my_plugins ディレクトリを作成し以下のファイルを格納。
substr()と同じ働きをする修飾子を作成する。

【/path/to/my_plugins/modifier.substr.php】
※ファイル名は「modifier.修飾子.php」とする。(関数の場合はfunction.関数名.php)

<?php
function smarty_modifier_substr ($string, $start, $length = ‘dummy’)
{
if($length == ‘dummy’) return substr($string, $start);
return substr($string, $start, $length);
}
?>
※関数名は「smarty_modifier_修飾子」とする。

□[HomeDir]/public_html/index.phpを以下の様に修正

<?php
//呼び出すクラスを拡張したクラスに変更
include_once(“/path/to/MySmarty.php”);

$smarty = new MySmarty();

$var = “VarName”;
$smarty->assign(“name”,$var);

$smarty->display(“template.tpl”);
?>

□/path/to/templates/template.tplを以下の様に修正

<html>
<body>
{$name|substr:0:3}
</body>
</html>

ブラウザで[HomeDir]/public_html/index.phpにアクセスして
$name(VarName)が3文字(Var)だけ表示されればOK

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA