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>自动调用: '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>效果: 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" />效果:ThinkPHP 是一个免费开源的,快速、简单的面向对象的 轻量级PHP开发框架 ,创立于2006年初,遵循Apache2开源协议发布,是为了敏捷WEB应用开发和简化企业应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。并且拥有众多的原创功能和特性,在社区团队的积极参与下,在易用性、扩展性和性能方面不断优化和改进,已经成长为国内最领先和最具影响力的WEB应用开发框架,众多的典型案例确保可以稳定用于商业以及门户级的开发。