好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

thinkphp 自定义标签 - Thinkphp

thinkphp 自定义标签

有了模板标签让网站前台开发更加快速和简单,更能节省时间原本由程序员来完成的工作,现在只要懂得html代码就能自己建设出属于自己的网站,接触过dedecms、phpcms等内容管理系统的人都知道,cms的前台都是使用模板标签来调用数据,例如调用文章列表

dedecms:

<ul>  {dede:arclist row= '10'  orderby= 'id desc'  titlelen= '' }            <li>[field:title]</li>  {/dede:arclist}  </ul>  phpcms:  <ul>  {pc:content action= "hits"  catid= "6"  num= "10"  order= "views DESC" }       {loop  $data   $r }         <li>{ $r [title]}</li>       {/loop}  {/pc}  </ul> 

这就是它们强大之处,接下来介绍一下THINKPHP强大的TAG扩展库,thinkphp自带以个tag扩展库只要我们继承TagLib就能随心所遇的定义属于自己的标签.

命名规范:

TagLib+标签库名称.class.php

例子下面的例子是实现调用导航,文件名称TagLibNav.class.php

<?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 调用方式:

< 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 >  

配置文件

'APP_AUTOLOAD_PATH'=>'@.TagLib', //TagLib的位置   @.表示当前文件夹下

'TAGLIB_BUILD_IN'=>'Cx,Nav',  //Cx是thinkphp基础类库的名称必须引用否则volist等标签就无法使用,Nav是自己定义的标签名称

控制器:

<?php  class  IndexAction  extends  Action{       public   function  index() {           $this ->display();      }  }  ?> 

这样在控制器中就不用写很多的代码咯,是不是很轻松?

查看更多关于thinkphp 自定义标签 - Thinkphp的详细内容...

  阅读:93次