一个为 CMS 系统设计的高性能 Go 语言模板引擎,提供了强大的标签系统和灵活的模板解析功能。该引擎特别适合构建现代化的内容管理系统,支持自定义标签处理器、多级缓存和丰富的数据处理能力。
🚀 高性能设计
🔧 灵活的扩展性
📝 完整的标签系统
{thinkcms:xxx}...{/thinkcms:xxx}[xxx:yyy]{__CONSTANT__}{$VARIABLE}🛡️ 可靠性保证
go get cnb.cool/jun3.work/template/engine
package main
import (
"fmt"
"cnb.cool/jun3.work/template/engine"
)
func main() {
// 创建模板引擎实例
e := engine.New(
// 设置标签前缀(默认为 "thinkcms")
engine.WithLabel("thinkcms"),
// 设置全局常量
engine.WithConstantForKV("__SITE_NAME__", "我的网站"),
// 设置全局变量
engine.WithVariableForKV("current_user", "admin"),
)
// 解析模板
template := `
<div class="header">
<h1>{__SITE_NAME__}</h1>
<p>欢迎, {$current_user}!</p>
</div>
{thinkcms:article limit="5" order="id desc"}
<div class="article">
<h2>[article:title]</h2>
<p>[article:content len="100"]</p>
<span>发布于: [article:time style="Y-m-d"]</span>
</div>
{/thinkcms:article}
`
result, err := e.Parse("home_page", template, nil)
if err != nil {
panic(err)
}
fmt.Println(result)
}
引擎核心结构体,管理整个模板解析流程:
type Engine struct {
handlers map[string]tag.TagHandler // 标签处理器映射
constant map[string]interface{} // 全局常量
variable *Variable // 全局变量
label string // 标签前缀
cache cache.Cache // 缓存实现
}
自定义标签处理器需要实现的接口:
type TagHandler interface {
// 处理内联标签
HandleInline(tag string, field string, attrs map[string]string, data Context) (string, error)
// 生成数据
MakeData(tag string, attrs map[string]string) ([]any, error)
}
标签处理上下文:
type Context struct {
Data any // 当前数据
Index int // 当前索引
}
提供了一系列配置选项函数:
// 设置标签前缀
engine.WithLabel("thinkcms")
// 设置缓存实现
engine.WithCache(myCache)
// 设置常量
engine.WithConstant(map[string]interface{}{
"__SITE_NAME__": "我的网站",
})
// 设置变量
engine.WithVariable(map[string]interface{}{
"user": "admin",
})
// 注册标签处理器
engine.WithTagHandler("article", &ArticleHandler{})
{__CONSTANT_NAME__}
{$VARIABLE_NAME}
{thinkcms:tag_name attr1="value1" attr2="value2"} 内容 {/thinkcms:tag_name}
[tag_name:field_name len="100" style="Y-m-d"]
常用属性说明:
len: 字符串长度限制style: 时间格式化样式where: 条件过滤order: 排序规则limit: 数量限制table: 数据表名支持多种缓存实现:
// 1. 空缓存(默认,用于开发)
cache := empty.New()
// 2. 内存缓存
cache := memory.New()
// 3. 文件缓存
cache := file.New("/path/to/cache")
// 4. 自定义缓存
type MyCache struct {
// 实现 cache.Cache 接口
}
引擎提供了完善的错误处理机制:
result, err := engine.Parse("template_name", template, data)
if err != nil {
switch err.(type) {
case *ParseError:
// 处理解析错误
case *ExecuteError:
// 处理执行错误
default:
// 处理其他错误
}
}
欢迎提交 Issue 和 Pull Request。在提交代码前,请确保:
MIT License