Smartyの使い方サンプル
PHPだとテンプレートエンジンとしてSmartyを使うことが個人的には多いのですが、
他の人はどう使っているのかな?と思いつつ、自分はこう使っているというメモ。
Smaryt を直接呼び出さずに継承クラスを使って利用してます。
(クラス変数としてSmartyオブジェクトを持つ形式もあったのですが、使い勝手が悪そうなのでとりあえずパス)
で、例ですが、継承クラスSdSmarty を定義しているソース。
(SdSmarty.class.php とかしている)
[php num=1]
function _get_smarty_prefilter($source,&$smarty){
return mb_convert_encoding( $source, mb_internal_encoding(), 'SJIS');
}
function _get_smarty_outputfilter($source,&$smaty){ return mb_convert_encoding( $source, 'SJIS', mb_internal_encoding()); }
class SdSmarty extends Smarty {
function SdSmarty(){
$this->left_delimiter='<{';
$this->right_delimiter='}>';
$this->template_dir = DIR_BASE.'template/';
$this->compile_dir = DIR_BASE.'templates_c/';
$this->config_dir = DIR_BASE.'config/';
$this->cache_dir = DIR_BASE.'cache/';
$this->register_prefilter('_get_smarty_prefilter');
$this->register_outputfilter('_get_smarty_outputfilter');
$this->security = true;
}
}
[/php]
left_delimiter、right_delimiter は パラメータの区分文字列で、通常は「{」「}」なのですが、
テンプレートにJavaScriptなどがある場合、使い勝手が悪いので、Xoops風にしてます。
template_dir、compile_dir、config_dir、cache_dir はテンプレートディレクトリ等の設定。
DIR_BASE を別の設定ファイル等で定義するようにしておいてます。
「定義子としてDIR_BASEはベースとなるディレクトリを設定する」そのルールさえ守っていれば、まぁ割と汎用的に使えるかな、と。
regist_prefilter、register_outputfilter は「テンプレート解析前処理」「テンプレート解析後処理」を定義しておけます。
上のサンプルではテンプレートファイルがSJISで記述されていると仮定して、文字コード変換処理を設定してます。
security は セキュリティの設定です。
Smartyの中でもちょっと危なそうな処理を制限します。
http://sunset.freespace.jp/smarty/SmartyManual_261J_html/variable.security.html
でもって、実際に呼び出しているソース。
[php num=1]
$smarty = new SdSmarty();
$smarty->assign( 'username', $username );
$smarty->display( 'list_user.html');
[/php]
特に変わったことしてないですね。
まぁ大体こんなものではないでしょうか。