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