看了dedecms的标签,觉得很方便,但毕竟是别人开发的,有时候想添加一些新的自己的功能还是有局限,所以今天在网上搜了下如何用smarty模板构建自定义标签。
1、首先下载smarty模板,然后定义smarty模板的环境,init.php。数据库连接类mysql.php这里就不写了。
<?php
require_once('include/config.inc.php');
require_once('class/mysql.php');
require_once('smarty/smarty.class.php');
$db=new mysql(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME,'','gb2312');
$smarty=new Smarty;
$smarty->template_dir='templates';
$smarty->cache_dir='caches';
$smarty->compile_dir='compiled';
$smarty->left_delimiter = '<{';
$smarty->right_delimiter = '}>'
?>
2、编写标签主要代码lib.arclist.php
<?php
function arclist($args, $content, &$smarty){
$num=$args["num"];
$cat_id=$args["cat_id"];
$sql="select article_id,title from article";
$w="";
$n="";
if($cat_id!="")
{
$w=" where cat_id=".$args["cat_id"]." order by article_id desc ";
}
if($num!=""){
$w=" limit 0,".$args["num"];
}
if($cat_id=="" && $num=="")
{
$w=" order by article_id desc limit 0,6";
}
$sql=$sql.$w;
$res=$GLOBALS['db']->query($sql);
while($row=$GLOBALS['db']->fetch_array($res)){
$article_id=$row['article_id'];
//$arr[]=array('id' => $row['article_id'],'title' => $row['title']);
$arr[$article_id]['id']=$row['article_id'];
$arr[$article_id]['title']=$row['title'];
$arr[$article_id]['url']=$row['article_id'].".html";
//$arr[$article_id]['url']="detail.php?id=".$row['article_id'];
}
$smarty->assign("list",$arr);
return $content;
}
?>
3、标签注册并在文件中引用
<?php
require_once('init.php');
require_once('libs/lib.arclist.php');
$smarty->registerPlugin("block","arclist","arclist"); //注册block,这个就是应用标签的基础
$smarty->display('news.html');
?>
4、模板文件news.html代码截取
<{arclist cat_id='21' num='10'}>
<{foreach from=$list item=v}>
<li><a href="#"><{$v.title}></a></li>
<{/foreach}>
<{/arclist}>