smarty循环基础

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");

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值