查看文章
 
Smarty之foreach心得
2008-04-05 6:04

New title:First post body
New title:First post body
New title:First post body
New title:First post body
New title:First post body
New title:First post body
New title:First post body
New title:First post body
New title:First post body
New title:First post body
New title:First post body
New title:First post body
New title:First post body
New title:First post body
New title:First post body

<?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的原理了,不过说实在的,还有其它的几个参数还没有测试,一般用得最多

的都是这两个参数 itemfrom。其中item是决定循环次数,from的值是从$smarty->assign这里替换的变量,如上面的yes,test.tpl模板那边的from必须为yes,否则无法接收到值,在test.tpl中,item

啥,下面的 $news.title一定要和item的值相同,除非用数组的下标形式来循环,否则无法输出结果


类别:默认分类||添加到搜藏 |分享到i贴吧|浏览(1399)|评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
     

   
帮助中心 | 空间客服 | 投诉中心 | 空间协议
©2012 Baidu