Home > php教程 > php手册 > body text

ThinkPHP模板自定义标签使用方法

WBOY
Release: 2016-06-13 09:31:56
Original
1066 people have browsed it

使用模板标签可以让网站前台开发更加快速和简单,使用过dedecms、phpcms等内容管理系统的人应该都知道,cms的前台都是使用模板标签来调用数据。以调用文章列表为例:

dedecms可以写成:

<ul>
{dede:arclist row='10' orderby='id desc' titlelen=''}
     <li>[field:title]</li>
{/dede:arclist}
</ul>
Copy after login

phpcms可以写成:

<ul>
{pc:content action="hits" catid="6" num="10" order="views DESC"}
   {loop $data $r}
    <li>{$r[title]}</li>
   {/loop}
{/pc}
</ul>
Copy after login

ThinkPHP的自定义标签同样能够实现这样强大的功能。ThinkPHP自定义标签通过TAG扩展库来实现。而ThinkPHP本身就自带了一个tag扩展库只要我们继承TagLib就能随心所遇的定义属于自己的标签。

命名规范:

TagLib+标签库名称.class.php

下面以实现调用导航为例加以说明

文件TagLibNav.class.php如下:

<&#63;php
class TagLibNav extends TagLib {
  //attr 属性列表 
  //close 是否闭合(0 或者1 默认1)
  //alias 标签别名
  //level 嵌套层次
  // 标签定义如下:
  protected $tags = array(
    'nav' => array('attr' => 'limit,order', 'level' => 3,'close'=>1),
  );
  //定义查询数据库标签
  //attr是属性列表,$content是存储标签之间的内容的
  public function _nav($attr, $content) {
    $tag=$this->parseXmlAttr($attr,$content);
    $cate=M('Channel');
    $tb=$cate->order($tag['order'])->limit($tag['limit'])->select();
    $str='';
    for($i=0;$i<count($tb);$i++)
    {
     $c=str_replace(array("[filed:id]","[filed:name]"),array($tb[$i]['id'],$tb[$i]['name']),$content);
     $str.=$c;
    }
    return $str;
  }
}
&#63;>
Copy after login

html页面调用方式:

<tagLib name="nav" />     //必须在头部进行引用否则会出错
<html>
<head>
 <title>tablist</title>
</head>
<body>
  <div class="nav">
   <ul>
    <li>首页</li>
    <nav:nav limit='4' order='id asc'>
     <li><a href="[filed:id]">[filed:name]</a></li>
    </nav:nav>
   </ul>
 </div>
 </body>
</html>
Copy after login

配置文件:

'APP_AUTOLOAD_PATH'=>'@.TagLib',  //TagLib的位置  @.表示当前文件夹下
'TAGLIB_BUILD_IN'=>'Cx,Nav',       //Cx是thinkphp基础类库的名称必须引用否则volist等标签就无法使用,Nav是自己定义的标签名称
Copy after login

控制器:

<&#63;php
class IndexAction extends Action{
  public function index() {
    $this->display();
  }
}
&#63;>
Copy after login

至此实现了自定义标签,在控制器中也不用写很多的代码了。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!