ループ回数(iterationプロパティ)
広告
ループ回数は「iteration」プロパティで参照することができます。
$smarty.foreach.ループ名.iteration
ループ内で記述することでループされた回数を取得することが出来ます。最初のループのループ回数は「1」からとなります。
例えば次のように記述します。
{foreach from=$personaldata item=var name=loopname} <p>({$smarty.foreach.loopname.iteration}){$var}</p> {/foreach}
ループが1度回る度にループの回数とその時の要素を表示します。
サンプルプログラム
では簡単なサンプルプログラムを作成して試してみます。
<?php require_once('Smarty.class.php'); $smarty = new Smarty(); $smarty->template_dir = 'd:/smartysample/foreach/templates/'; $smarty->compile_dir = 'd:/smartysample/foreach/templates_c/'; $smarty->config_dir = 'd:/smartysample/foreach/configs/'; $smarty->cache_dir = 'd:/smartysample/foreach/cache/'; $smarty->assign('title', '繰り返し処理のテスト'); $data = array( "name"=>"Yamada", "old"=>"24", "address"=>"Tokyo" ); $smarty->assign('personaldata', $data); $smarty->display('sample4-1.tpl'); ?>
上記を「sample4-1.php」の名前で「(Apacheドキュメントルート)¥smarty¥foreach」に保存します。
{* Smarty foreach/sample4-1.tpl *} <html> <head> <title>Smarty Test</title> </head> <body> <h1>{$title}</h1> {foreach from=$personaldata item=var name=loopname} <p>({$smarty.foreach.loopname.iteration}) {$var}</p> {/foreach} </body> </html>
上記を「sample4-1.tpl」の名前で「D:¥smartysample¥foreach¥templates」に保存します。
そしてブラウザから「http://localhost/smarty/foreach/sample4-1.php」へアクセスして下さい。
( Written by Tatsuo Ikura )