<?php
/*@file:class/MSmarty_class.php
*
* @title:类,将使用smarty的前三个步聚封起
*
* @author:virhuiai
*
* @date:03-21-2013
*
* @modified:
* 03-23-2013
*
*
*/
date_default_timezone_set('PRC');
//require_once('/usr/lib64/php/Smarty/Smarty.class.php');
require_once( 'Smarty/Smarty.class.php' );
class MSmarty extends Smarty{
function __construct(){
parent::__construct();
$this->setTemplateDir('/home/virhuiai/html/test/smarty/templates');
$this->setCompileDir('/home/virhuiai/html/test/smarty/templates_c');
$this->setConfigDir('/home/virhuiai/html/test/smarty/configs');
$this->setCacheDir('/home/virhuiai/html/test/smarty/cache');
$this->caching = Smarty::CACHING_LIFETIME_CURRENT;
$this->assign('app_name', 'Guest Book');
}
}
$smarty = new MSmarty();
//$smarty->right_delimiter='{{';
//$smarty->right_delimiter = '}}';
$right_delimiter='{{';
$right_delimiter = '}}';
//$smarty->assign('name','virhuiai');
//$smarty->display('setup.tpl');
?>
2. try_seciton.php
<?php
/*@file:try_seciton.php
*
* @title:类,将使用smarty的前三个步聚封起
*
* @author:virhuiai
*
* @date:03-21-2013
*
* @modified:03-23-2013
*
*/
include_once './class/MSmarty_class.php';
$arr = array(
array('id'=>1,'title'=>'title1'),
array('id'=>2,'title'=>'title2'),
array('id'=>3,'title'=>'title3')
);
$smarty->assign('news',$arr);
$smarty->display('try_section.tpl');
?>
3.
try_seciton.tpl
{section name=sn loop=$news}
{if $smarty.section.sn.first}
<table>
<th>id</th>
<th>title</th>
{/if}
<tr>
<td>{$news[sn].id}</td>
<td>{$news[sn].title}</td>
</tr>
{if $smarty.section.sn.last}
</table>
{/if}
{sectionelse}
there is no news.
{/section}
显示结果如下(是一个表格的样子,以下显示的没有加样式):
id title
1 title1
2 title2
3 title3
可以看出,无论是索引还是关联数组用起来都是很方便。下面介绍下section中各个属性的说明:
1、section中的属性
name:(必选) 是section循环的名称只是标示循环唯一的名字没有特别意义,前面没有$符号;
loop: (必选)是在php声明中的变量名称,用来标示是循环哪一个数组(即要循环数组名)需要使用$;
start: (可选)循环执行的初始位置. 如果该值为负数,开始位置从数组的尾部算起. 例如:如果数组中有7个元素,指定start为-2,那么指向当前数组的索引为5. 非法值(超过了循环数组的下限)将被自动调整为最接近的合法值.
step: (可选)如其它语言的循环,是一个步长,如果为负数,则倒序循环;
max:(可选)循环的最大下标,如果是1则只循环1次,如果为2则循环2次;
show:(可选)默认为true即显示。如果设置了{sectionelse}。表示如果数组没有内容的时候显示这部分的内容;如果show为false则显示这部分。如果没有设置{sectionelse}则不输出该数组。
2、smarty中section中的变量
index:用于显示当前循环的索引,从0开始(如果指定了start属性,那么由该值开始),每次加1(如果指定了step属性,那么由该值决定).如果没有指定step和start属性,此值的作用和iteration类似,只不过从0开始而已.
index_prev:用于显示上一个循环索引值. 循环开始时,此值为-1.
index_next:用于显示下一个循环索引值. 循环执行到最后一次时,此值仍然比当前索引值大1(如果指定了step,取决于此值).
iteration:用于显示循环的次数.iteration 不像index属性受start、step和max属性的影响,该值总是从1开始(index是从0开始的).rownum 是iteration的别名,两者等同.
first:如果当前循环第一次执行,first 被设置为true.
last:如果当前循环执行到最后一次,last 被设置为true.
rownum:用于显示循环的次数. 该属性是iteration的别名,两者等同.
loop:用于显示该循环上一次循环时的索引值. 该值可以用于循环内部或循环结束后.
show:是 section 的参数. show 取值为布尔值 true 或 false. 如果设置为 false,该循环将不显示. 如果指定了 sectionelse 子句,该字句是否显示也取决于该值.
total:用于显示循环执行总的次数. 可以在循环中或执行结束后调用此属性.