smarty里section的一些常用方法和补充知识(转)

作者:跑调 发布时间:July 17, 2011 分类:开源路漫漫兮 3 Comments

smarty中section的使用
在smarty的使用过程中,有很多时候需要将一个数组输出到模板中来处理,以下将演示如何将一个索引(index)数组和关联(assocaite)数组在页面中展现出来。

本文中假设有如下一个索引数组

1、索引数组

 $people = array('tony','sweety','abc','four');
 $smarty->assign('people',$people);

在模板中显示:

 {section name=n loop=$people}
     name:{$people[n]}
{/section}

这样在模板中就可以显示出这个数组的内容了。结果如下:
1 name:tony
2 name:sweety
3 name:abc
4 name:four

2、关联数组

     $arr = array(
         array('id'=>1,'title'=>'title1'),
         array('id'=>2,'title'=>'title2'),
         array('id'=>3,'title'=>'title3')
     );
     
     $smarty->assign('news',$arr);

在模板中显示过程如下

 {section name=sn loop=$news}
     {if $smarty.section.sn.first}
          
      {/if}
      
     {if $smarty.section.sn.last}
         
id title
{$news[sn].id} {$news[sn].title}
{/if} {sectionelse} there is no news. {/section}

显示结果如下(是一个表格的样子,以下显示的没有加样式):

 id title 
1 title1 
2 title2 
3 title3 

可以看出,无论是索引还是关联数组用起来都是很方便。下面介绍下section中各个属性的说明:

阅读剩余部分...