模板标签让网站前台开发更加快速和简单,通常用于某个标签库需要被大多数模板使用的情况。接触过dedecms或者phpcms等内容管理系统的人都知道,cms的前台都是使用模板标签来调用数据,如列表,内容。
{pc:content action="hits" catid="6" num="10" order="views DESC"} {loop $data $r}
{$r[title]}
{/loop}{/pc}
1.新建标签库文件,自定义标签,Application/Common/LibTag/Other.class.php
<?php
namespace Common\LibTag;
use Think\Template\TagLib;//自定义标签库
class Other extends TagLib{
protected $tags = array(
//自定义标签
'xxxtest' => array(
'attr' => 'a,b,test', // attr 属性列表
'close' => 1
/**
* close 标签是否闭合(0 或者1 默认为1,表示闭合)
* <article:read>...</article:read>就是闭合标签,起始和结束标签必须成对出现。
* 如果是<article:read name="hello" /> 就是开放标签。
**/
),
'echofun' => array( 'close' => 1 ),
);
}
2.Application/Home/Conf/config.php 下自定义加载自定义标签
<?php
return array(
//加载自定义标签
'TAGLIB_PRE_LOAD'=>'Common\\LibTag\\Other',//预加载的tag
'TAGLIB_BUILD_IN' => 'cx', //内置标签
);
3.Application/Home/Controller/TestController.class.php 调用View展示
<?php
namespace Home\Controller;
use Think\Controller;
header("Content-type: text/html; charset=utf-8");
class TestController extends Controller {
// 测试标签库用法
public function testTags(){
$this->display();
}
}
4.Application/Home/View/Test/testTags.html
this is template 测试标签库
<br />
xxxtest是闭合标签 <other:xxxtest a='a' b='b' test='test'>content</other:xxxtest>
<br />
echofun是闭合标签
<other:echofun>
{$echofun}
</other:echofun>
输出结果
this is template 测试标签库
xxxtest是闭合标签 attr->{"a":"a","b":"b","test":"test"} content->content END
echofun是闭合标签 1234
标签库可在模板传参返回展示,可自定义封装列表、分页、内容展示等。如有不解之处多结合文章示例和官方文档看几遍