Smarty之foreach心得

运行结果:

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的值相同,除非用数组的下标形式来循环,否则无法输出结果

 

 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值