Home > Article > Backend Development > How to use ThinkPHP template custom tags_PHP tutorial
Using template tags can make website front-end development faster and simpler. Anyone who has used content management systems such as dedecms and phpcms should know that the front-end of cms uses template tags to call data. Take calling the article list as an example:
dedecms can be written as:
<ul> {dede:arclist row='10' orderby='id desc' titlelen=''} <li>[field:title]</li> {/dede:arclist} </ul>
phpcms can be written as:
<ul> {pc:content action="hits" catid="6" num="10" order="views DESC"} {loop $data $r} <li>{$r[title]}</li> {/loop} {/pc} </ul>
ThinkPHP’s custom tags can also achieve such powerful functions. ThinkPHP custom tags are implemented through the TAG extension library. ThinkPHP itself comes with a tag extension library. As long as we inherit TagLib, we can define our own tags as we like.
Naming convention:
TagLib+tag library name.class.php
The following takes the implementation of calling navigation as an example to illustrate
The file TagLibNav.class.php is as follows:
<?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; } } ?>
HTML page calling method:
<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>
Configuration file:
'APP_AUTOLOAD_PATH'=>'@.TagLib', //TagLib的位置 @.表示当前文件夹下 'TAGLIB_BUILD_IN'=>'Cx,Nav', //Cx是thinkphp基础类库的名称必须引用否则volist等标签就无法使用,Nav是自己定义的标签名称
Controller:
<?php class IndexAction extends Action{ public function index() { $this->display(); } } ?>
Custom tags are now implemented, and there is no need to write a lot of code in the controller.