Smarty一些小技巧
2009年4月13日
Smarty, PHP的一个非常出名的模板引擎, 很少用, 最近用了一点, 记录一些心得以备日后查阅.
1. 使用Smarty进行循环嵌套
// 在这里定义$sec1为一个二维数组 $sec1 = $db->fetchAll("select * from category"); for($i=0; $i<count($sec1); $i++) { $sec1[$i]['news'] = $db->fetchAll("select * from news where cid = ".$sec1[$i]['id']." order by id desc limit 0, 5"); } $smarty->assign('sec1', $sec1); $smarty->left_delimiter = "<{"; $smarty->right_delimiter = "}>"; $smarty->display('news.html');
// 模版文件
<{section name=sec1 loop=$sec1}> <div class="inner"> <h1><a href="/category/<{$sec1[sec1].id}>.html"><{$sec1[sec1].name}></a></h1> <ul> <{section name=sec2 loop=$sec1[sec1].news}> <li> <a href="/news/<{$sec1[sec1].news[sec2].id}>.html" target="_blank"> <{$sec1[sec1].news[sec2].title}> </a> </li> <{/section}> </ul> </div> <{/section}>
2. Smarty对于类似分页情况时的多参数缓存
我们都知道可以通过$smarty->display(’NewsList.tpl’, $page)这样来实现类似与NewsList.php?page=1这样URL结构相同的情况缓存. 但是如果情况是NewsList.php?cid=1&Page=1这样呢? 或许大家也知道, 但是我今天在网上查阅了一下才知道原来这么简单,$smarty->display(’NewsList.tpl’, “cid:{$cid}-page:{$page}”)就可以了. 呵呵
Recent Comments