Smarty フィルタ
| プリフィルタ | テンプレートがコンパイルされる前に実行されるユーザ定義処理。 |
| ポストフィルタ | テンプレートがコンパイルされた後に実行されるユーザ定義処理。 |
| アウトプットフィルタ | テンプレートがdisplay()又はfetch()を経由して呼び出された時に実行されるユーザ定義処理。 |
| この機能は意外と便利なものです。 使うタイミングによってはパフォーマンスを上げることができます。 他にもキャッシュハンドラ関数など特質すべき機能が用意されています。 |
|
smarty.php
require_once "../include/define.php"; require_once SMARTY_DIR."Smarty.class.php"; /** * [プリフィルタ] * URLにAタグをつける * * 第一引数: string型 $tpl_source * 第二引数: Smarty型 $smarty * 戻り : 処理後のテンプレートソース */ function tpl_url2link($tpl_source, &$smarty) { $ptn = "/(https?)(://[wS+$?.%,!#~*/:@&=-]+)/i"; $rpc = "<a href=\"\1\2\" target=\"_top\">\1\2</a>"; return preg_replace($ptn, $rpc, $tpl_source); } /** * Smartyヘルプより [ポストフィルタ] * ヘッダー行の追加 * * 第一引数: string型 $tpl_source * 第二引数: Smarty型 $smarty * 戻り : 処理後のテンプレートソース */ function add_header_comment($tpl_source, &$smarty) { /* コンパイル後のファイルがPHPのソースであるため PHPの構文を挿入する必要があります。 */ return "<?php echo \"<!-- Created by Smarty! -->n\" ?>n" .$tpl_source; } /** * [アウトプットフィルタ] * 文字エンコードの変換 * * 第一引数: string型 $tpl_output * 第二引数: Smarty型 $smarty * 戻り : 処理後のアウトプットソース */ function tpl_euc2sjis($tpl_output, &$smarty) { return mb_convert_encoding($tpl_output, "SJIS", "EUC-JP"); } /* Smartyオブジェクトの生成 */ $tpl = new Smarty; $tpl->template_dir = TEMPLATE_DIR; $tpl->compile_dir = COMPILE_DIR; $tpl->config_dir = CONFIG_DIR; $tpl->cache_dir = CACHE_DIR; /* プリフィルタを登録する */ $tpl->register_prefilter('tpl_url2link'); /* ポストフィルタを登録する */ $tpl->register_postfilter('add_header_comment'); /* アウトプットフィルタを登録する */ $tpl->register_outputfilter('tpl_euc2sjis'); /* テンプレートファイルの読み込みと表示 */ $tpl->display('Smarty.tpl');
処理ステップ
|
テンプレートソース [プリフィルタ] コンパイル処理(PHPソースの生成) [ポストフィルタ] テンプレート処理 [アウトプットフィルタ] 表示(データ出力) |
