学习自定义标签时,请查看手册(扩展->标签库)中的相关介绍
http://document.thinkphp.cn/manual_3_2.html#taglib_driver
主要分三步:
一、自定义标签(新建Test.class.php文件)
namespace Think\Template\TagLib; // 当前文件所在的目录
use Think\Template\TagLib; // Template目录下的TagLib.class.php文件
class Test extends TagLib {
protected $tags = array(
// 定义标签
'edit' => array('attr'=>'type,name,id,value','close'=>0), // 调用这个标签,就是映射到真正的input标签(因为返回的就是input标签),这里不过是换了一个名称而已
'content' => array('attr'=>'name,id'), // 原理同上
);
// edit标签解析(每个标签的解析方法在定义的时候需要添加“_”前缀)
public function _edit($tag) {
$name = $tag['name'];
$id = $tag['id'];
$type = $tag['type'];
$value = $tag['value'];
$str = "<input type='".$type."' id='".$id."' name='".$name."' value='".$value."' />";
return $str;
}
// content标签解析
public function _content($tag,$content) {
$name = $tag['name'];
$id = $tag['id'];
$str = '<textarea id="'.$id.'" name="'.$name.'">'.$content.'</textarea>';
return $str;
}
}二、赋值变量,输出模板 public function index(){
$this->assign('value', 'hello world !');
$this->display('tag');
}三、在模板中输出<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<taglib name='Test' /><!-- 指定标签库 -->
<test:edit type='input' id='test' name='mail' value='{$value}' />
<hr/>
<test:content id="content" name="content">{$value}</test:content>
</body>
</html>自动调用:要在config文件里加上如下配置:
'TAGLIB_LOAD'=>true,
'APP_AUTOLOAD_PATH'=>'@.TagLib',
'TAGLIB_BUILD_IN'=>'Cx,Test',然后模板输出就要这样写了(不需要写test:前缀和<taglib name='Test' />了): <edit type='input' id='test' name='mail' value='{$value}' />
<hr/>
<content id="content" name="content">{$value}</content>效果:
简单理解,所谓自定义标签就是看返回的是什么,如果返回的是html标签,那就以html标签展现出来;如果返回的是纯数据,那就以文本的形式展现出来(组装从sql取出来的数据为多)
protected $tags = array(
'data' => array('attr'=>'type','close'=>0), // input标签
);
public function _data($tag) {
switch ($tag['type']) {
case 1:
return '<div style="color: red;">返回的是类型1</div>';
break;
case 2:
return '<div style="color: blue;">返回的是类型1</div>';
break;
default:
return '<div style="color: green;">默认类型</div>';
break;
}
}模板渲染: <data />
<data type="1" />
<data type="2" />效果:
谢谢关注~
