logo
0
0
Login
重构模板引擎,新增标签处理器接口和上下文结构,优化标签处理逻辑,调整示例代码以展示新功能,更新文档以反映最新的接口变更。

Template Engine

一个为 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) }

核心组件

Engine

引擎核心结构体,管理整个模板解析流程:

type Engine struct { handlers map[string]tag.TagHandler // 标签处理器映射 constant map[string]interface{} // 全局常量 variable *Variable // 全局变量 label string // 标签前缀 cache cache.Cache // 缓存实现 }

TagHandler 接口

自定义标签处理器需要实现的接口:

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) }

Context 结构体

标签处理上下文:

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{})

标签语法

1. 常量标签

{__CONSTANT_NAME__}

2. 变量标签

{$VARIABLE_NAME}

3. 块级标签

{thinkcms:tag_name attr1="value1" attr2="value2"} 内容 {/thinkcms:tag_name}

4. 内联标签

[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。在提交代码前,请确保:

  1. 代码符合 Go 代码规范
  2. 添加了必要的测试用例
  3. 更新了相关文档
  4. 提交信息清晰明了

许可证

MIT License