PHPが動作する任意の場所にPHPファイルを作成し、以下の内容を記述してください。
define( 'SMARTY_DIR', '/tmp/Smarty/libs/' );
require_once( SMARTY_DIR . 'Smarty.class.php' );
$smarty = new Smarty();
// 各ディレクトリの設定
$smarty->template_dir = '/tmp/Smarty/templates/';
$smarty->compile_dir = '/tmp/Smarty/templates_c/';
$smarty->config_dir = '/tmp/Smarty/configs/';
$smarty->cache_dir = '/tmp/Smarty/cache/';
// コンボボックスに表示する要素を配列で宣言する
$colors['red'] = '赤';
$colors['blue'] = '青';
$colors['yellow'] = '黄';
// 宣言した配列を、変数「$colorArray」にセットします
// この変数がコンボボックスの要素として指定されます
$smarty->assign( 'colorArray', $colors );
// コンボボックスで「青」が選択されている状態にするために、
// 変数「$selectColor」に 'blue' をセットします
$smarty->assign( 'selectColor', 'blue' );
// テンプレートファイルを表示
$smarty->display( 'test.tpl' );
「C:\tmp\Smarty\templates\test.tpl」 を作成して、以下の内容を記述してください。
<html>
{html_options name="color" options=$colorArray selected=$selectColor}
</html>
上で作成したPHPを実行してください。
以下のように表示されます。
リストボックスにしたい場合は、テンプレートファイルを以下のように「size」要素を記述します。
このように、selectタグが持っている要素を追記すれば、生成されたselectタグに反映されます。
<html>
{html_options name="type" options=$colorArray selected=$selectColor size=3}
</html>
[PHP - Smarty - 使い方]
基本の使用例 (文字列をテンプレートファイルに表示) 【assign】
条件分岐を行う 【if】
配列分ループを行う 【foreach】
HTMLのラジオボタンを使用する 【html_radios】
設定ファイルの内容を読み込む 【get_config_vars】