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 = array( 'red', 'blue', 'yellow' );
// 宣言した配列を、変数「$colorArray」にセットします
$smarty->assign( 'colorArray', $colors );
// テンプレートファイルを表示
$smarty->display( 'test.tpl' );
「C:\tmp\Smarty\templates\test.tpl」 を作成して、以下の内容を記述してください。
「form」に指定した配列変数の要素数分ループ処理が行われます。
ループ時に「key」に指定した変数に配列要素のキー項目がセットされ、「item」に指定した変数に配列要素の値がセットされます。
<html>
<ul>
{foreach from=$colorArray key=keyString item=valueString}
<li>{$keyString}: {$valueString}</li>
{/foreach}
</ul>
</html>
上で作成したPHPを実行してください。
以下のように表示されます。
0: red
1: blue
2: yellow
[PHP - Smarty - 使い方]
基本の使用例 (文字列をテンプレートファイルに表示) 【assign】
条件分岐を行う 【if】
HTMLのリストボックス・コンボボックスを使用する 【html_options】
HTMLのラジオボタンを使用する 【html_radios】
設定ファイルの内容を読み込む 【get_config_vars】