smarty模板主要提供了foreach和section两种方法来实现循环。
foreach的语法格式:
{foreach key=key1 item=item1 from=$array1}
{$item1}
{/foreach}
key1--------表示数组中的每一个键值
item1 ------------ 表示数组中的每一个元素
$array1-------表示传入的数组变量名称
------------------------------------------------------------------------------------------------------------------------------------------
eg:
<table width="100%" border="0" cellspacing="0" cellpadding="0">
{foreach key=key1 item=item1 from=$array1}
<tr>
<td>{$key1}</td>
<td>{$item1}</td>
</tr>
{/foreach}
</table>
<?php
require_once("init.php");
$array1 = array(1=>"simon",2=>"helen",3=>"petter",4=>"中国");
$smarty->assign("array1",$array1);
$smarty->display("test.html");
?>
-------------------------------------------------------------------------------------------------------------------------------------------
{section name=section1 loop=$array1}
{$array1[section1]}
{/section}
section1--------表示这个循环区域的名字
$array1 ---------- 表示传入的数组变量名称。
需要注意:传递给section的数组的键值必须是以0开始的正整数,否则数组中的内容不会正确地被section获得
eg:
<table width="100%" border="0" cellspacing="0" cellpadding="0">
{section name=section1 loop=$array1}
<tr>
<td></td>
<td>{$array1[section1]}</td>
</tr>
{/section}
</table>
<?php
require_once("init.php");
$array1 = array(0=>"sdfsd",1=>"sd23232",2=>"gggggg");
$smarty->assign("array1",$array1);
$smarty->display("section.html");
?>
-----------------------------------------------------------------------------------------------------------------------
<table width="100%" border="0" cellspacing="0" cellpadding="0">
{section name=sec1 loop=$array1}
<tr>
<td colspan="2">{$array1[sec1].category_name}</td>
</tr>
{section name=sec2 loop=$array1[sec1].item}
<tr>
<td>.</td>
<td>{$array1[sec1].item[sec2].item_name}</td>
</tr>
{/section}
{/section}
</table>
<?php
require_once("init.php");
$array1 = array(
array("category_id" =>1,"category_name"=>"水果","item"=>array(
array("item_id"=>1,"item_name"=>"苹果"),
array("item_id"=>2,"item_name"=>"梨"),
array("item_id"=>3,"item_name"=>"香蕉"))),
array("category_id" =>1,"category_name"=>"水果","item"=>array(
array("item_id"=>1,"item_name"=>"苹果"),
array("item_id"=>2,"item_name"=>"梨"),
array("item_id"=>3,"item_name"=>"香蕉"))),
array("category_id" =>1,"category_name"=>"水果","item"=>array(
array("item_id"=>1,"item_name"=>"苹果"),
array("item_id"=>2,"item_name"=>"梨"),
array("item_id"=>3,"item_name"=>"香蕉"))));
$smarty->assign("array1",$array1);
$smarty->display("category.html");
?>