php之smarty模板自定义标签

看了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}>



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值