ループ処理をネストで2つ以上使用したい時
一覧表示のときとかで使いますが
ループで一覧だすとき、更にその中の項目でもループしたいって時にはまった。
結論から言うとこうしないと期待通りに表示されなかった。
表のテンプレート側(test.tpl)
<!--BEGIN chart--> <table> <tr> <th>タイトル</th> <td>{TITLE}</td> </tr> <tr> <!--BEGIN education--> <tr> <th>学歴</th> <td>{EDUCATION}</td> </tr> <!--END education--> </table> <!--END chart-->
<?php for($i=0; $i<$row; $i++){ $rs = mysql_fetch_assoc($qry); //中にあるものを先に書く if($rs['education'] != "") { $tpl->setCurrentBlock('education'); $tpl->setVariable("EDUCATION", $rs['education']); $tpl->parseCurrentBlock('education'); } //包んでいる方を後に書く $tpl->setCurrentBlock('chart'); $tpl->setVariable("TITLE", $rs['title']); $tpl->parseCurrentBlock('chart'); } ?>
初めは裏のphpをこうやって書いてた。
<?php for($i=0; $i<$row; $i++){ $rs = mysql_fetch_assoc($qry); //包んでいる方 $tpl->setCurrentBlock('chart'); $tpl->setVariable("TITLE", $rs['title']); //中にあるもの if($rs['education'] != "") { $tpl->setCurrentBlock('education'); $tpl->setVariable("EDUCATION", $rs['education']); $tpl->parseCurrentBlock('education'); } $tpl->parseCurrentBlock('chart'); } ?>
参照
PHP Tips - ウェブ制作・ウェブシステム開発のキューブワークス
こちら↑のエントリに何故これじゃダメか考えてみてくださいって書いてあるけど・・・何故かよくわかんない><