1.新建自定义标签类App/Tag/
<?php
namespace App\Tag;
use App\HttpController\Common\Common;
use think\template\TagLib;
class My extends TagLib{
// 标签定义
protected $tags = [
// 标签定义: attr 属性列表 close 是否闭合(0 或者1 默认1) alias 标签别名 level 嵌套层次
'test' => ['attr' => ''],
'title' => ['attr' => '', 'close' => 0],
];
/**
* 测试标签解析
* 格式:
* {my:test}{$content}{/my:test}或{test}{$content}{/test}
* @access public
* @param array $tag 标签属性
* @param string $content 标签内容
* @return string
*/
public function tagTest(array $tag, string $content): string
{
$content = '<strong style="color: red">' . $content . '</strong>'; //测试内容自动加粗,红色字体
return $content;
}
/**
* 网站标题
* 格式:
* {my:title/}或者{title/}
* @access public
* @param array $tag 标签属性
* @return string
*/
public function tagTitle(array $tag): string
{
$system = Common::getSystem();//调用系统配置
return $system['title'];
}
}
2.在template.php中加入自定义标签配置 'taglib_pre_load' => '\App\Tag\My'
<?php
namespace App\Tools;
use EasySwoole\Template\RenderInterface;
class Template implements RenderInterface
{
protected $template;
function __construct()
{
$config = [
'view_path' => EASYSWOOLE_ROOT . '/App/Views/',
'cache_path' => EASYSWOOLE_ROOT . '/Temp/runtime/',
//如果放在内置标签库,使用标签不需要前缀 如{test}{/test}
// 'taglib_build_in' => 'cx,\App\Tag\My', // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔 注意解析顺序
//如果放在外置标签库,使用标签则需要前缀 如{my:test}{/my:test}
'taglib_pre_load' => '\App\Tag\My',// 需要额外加载的标签库(须指定标签库名称),多个以逗号分隔
];
$this->template = new \think\Template($config);
}
public function render(string $template,?array $data = null,?array $options = null):?string
{
// TODO: Implement render() method.
ob_start();
$this->template->assign($data);
$this->template->fetch($template);
$content = ob_get_contents() ;
return $content;
}
public function afterRender(?string $result, string $template, array $data = [], array $options = [])
{
// TODO: Implement afterRender() method.
}
public function onException(\Throwable $throwable,$arg): string
{
// TODO: Implement onException() method.
$msg = "{$throwable->getMessage()} at file:{$throwable->getFile()} line:{$throwable->getLine()}";
trigger_error($msg);
return $msg;
}
}
3.在要渲染的视图模板HTML文件使用标签
通过外置标签库配置使用方式
{my:test} {$user['username']} {/my:test} {my:title/}
通过内置标签库配置使用方式
{test} {$user['username']} {/test} {title/}
4.注意事项
修改自定义标签库需要删除缓存(/Temp/runtime/)和重启服务才会生效
本文为够意思原创文章,转载无需和我联系,但请注明来自够意思博客blog.go1s.cn:够意思博客 » EasySwoole中使用think-template模板实现自定义标签