自定义模板函数通过在app/common.php定义并注册到config/template.php,如format_time;自定义标签需创建继承TagLib的类并注册标签库,如Test标签输出Hello, ThinkPHP!。

ThinkPHP 模板引擎支持自定义标签和函数,方便开发者扩展功能。以下以 ThinkPHP 6 为例,介绍如何自定义模板标签和函数。
自定义模板函数
模板函数在模板中直接调用,常用于格式化数据、输出公共内容等。
步骤:
function format_time($time) {
return date('Y-m-d H:i:s', $time);
}
立即学习“PHP免费学习笔记(深入)”;
- 在配置文件 config/template.php 中注册函数:
'tpl_func' => [
'format_time' => 'app\common\format_time'
]
- 在模板中使用:
{$create_time|format_time}
自定义模板标签
模板标签用于实现更复杂的逻辑控制,比如循环、条件判断或调用模型数据。
步骤:
- 创建标签类,如 app/taglib/Test.php
- 类需继承 \think\template\TagLib,并定义标签规则:
namespace app\taglib;
use think\template\TagLib;
class Test extends TagLib
{
protected $tags = [
'hello' => ['close' => 1]
];
public function tagHello($tag, $content)
{
$name = $tag['name'] ?? 'World';
return '';
}
}
- 在 config/template.php 中注册标签库:
'taglib_pre_load' => 'app\taglib\Test'
- 在模板中使用:
注意事项
- 函数名和标签名避免与系统内置冲突
- 标签类命名空间要正确,路径与命名一致
- 编译后的标签会缓存,修改后可清空 runtime/temp 目录测试











