Smarty之foreach心得

Smarty之foreach心得
大家先看看运行结果:

新闻标题:新闻内容
新闻标题:新闻内容
新闻标题:新闻内容
新闻标题:新闻内容
新闻标题:新闻内容
新闻标题:新闻内容
新闻标题:新闻内容
新闻标题:新闻内容

<?php
require_once('./Smarty/libs/Smarty.class.php');
$db_host='localhost';
$db_user='root';
$db_password='';
$db_name='test';
mysql_connect($db_host,$db_user,$db_password);  //连接数据库
mysql_select_db($db_name);  //选择数据库
$sql="select * from posts";
$result=mysql_query($sql);  //查询
$smarty=new Smarty();  //实例化出一个$smarty对象
$smarty->templates_dir='templates';  //设置模板目录
$smarty->compile_dir='templates_c';  //设置编译目录
$smarty->left_delimiter='{';  //按我理解,这是脚本左分界符
$smarty->right_delimiter='}';  //右分界符

//抓取记录
while($row=mysql_fetch_array($result))
{$record[]=array(
    'title'=>$row['title'],
'body'=>$row['body'],);
}
$smarty->assign('yes', $record);//传说中的替换变量,即将$record赋给yes
$smarty->display('test.tpl');
?>

//----------test.tpl---------------------------------------------------------------------------------
{foreach item=news from=$yes}
{$news.title}:{$news.body}
<br>
{/foreach}
以前对Smarty中的foreach有点云里雾里,今天特别在论坛上找出了一个辉老大出的题目做了一下~~经过反复的测试,终于弄明白了这个foreach的原理了,不过说实在的,还有其它的几个参数还没有测试,一般用得最多
的都是这两个参数 item和from。其中item是决定循环次数,而from的值是从$smarty->assign这里替换的变量,如上面的yes,在test.tpl模板那边的from必须为yes,否则无法接收到值,在test.tpl中,item为
啥,下面的 $news.title一定要和item的值相同,除非用数组的下标形式来循环,否则无法输出结果