模板解析器
text/template组件:使用 text/template (opens new window) 解析模板。用于消息格式转换、内容模板化、数据适配等场景。支持丰富的模板语法和自定义函数扩展。
# 配置
| 字段 | 类型 | 说明 | 默认值 |
|---|---|---|---|
| template | string | 模板内容或模板文件路径。使用file:前缀表示文件路径,如file:/path/to/tpl.txt | 无 |
支持的模板变量:
.id- 消息ID.ts- 消息时间戳(毫秒).data- 原始消息内容.msg- 消息体对象(JSON类型时可用.msg.field访问字段).metadata- 消息元数据对象.msgType- 消息类型.dataType- 数据类型
模板示例:
{{ .msg.name }} - 获取消息中的name字段
{{ .metadata.deviceType }} - 获取元数据中的设备类型
{{ .msgType }} - 获取消息类型
{{ .ts }} - 获取消息时间戳
{{ if gt .msg.temperature 30 }}高温{{ else }}正常{{ end }} - 条件判断
{{ range .msg.items }}{{ .name }},{{ end }} - 遍历数组
{{ printf "%.2f" .msg.value }}` - 格式化数值
{{ .msg.name | upper }} - 转换为大写
{{ .msg.content | replace "old" "new" }} - 替换文本
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 配置示例
{
"id": "s1",
"type": "text/template",
"name": "模板转换",
"configuration": {
"template": "type:{{ .type}}"
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 自定义函数
组件基于 Go 标准库 text/template,在节点初始化时从全局函数表 funcs.TemplateFunc (opens new window) 加载所有已注册函数并绑定到模板引擎。上层应用可通过 github.com/rulego/rulego/builtin/funcs 包注册自定义函数,注册后即可在模板中像内置函数一样调用。
注册函数:
import (
"strings"
"text/template"
"github.com/rulego/rulego/builtin/funcs"
)
// 单个注册
funcs.TemplateFunc.Register("upper", strings.ToUpper)
// 批量注册
funcs.TemplateFunc.RegisterAll(template.FuncMap{
"upper": strings.ToUpper,
"replace": strings.ReplaceAll,
})
// 注销 / 查询
funcs.TemplateFunc.UnRegister("upper")
f, ok := funcs.TemplateFunc.Get("upper")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
在模板中使用:
{{ upper .msg.name }} {{/* 直接调用 */}}
{{ .msg.name | upper }} {{/* 通过管道调用 */}}
{{ replace .msg.content "old" "new" }} {{/* 多参数调用 */}}
1
2
3
2
3
内置函数:默认仅注册了
escape(转义反斜杠、双引号、换行等 JSON 特殊字符)。上文模板示例中出现的upper、replace等需通过上述方式自行注册。
# 注册时机(重要)
text/template 的函数表(FuncMap)必须在模板 Parse 之前 绑定,因此:
- ✅ 在
rulego.New(...)创建规则链之前 注册——对所有text/template节点生效。 - ❌ 节点初始化之后再注册——不生效,需要重新加载规则链使节点重新 Init 才会刷新函数快照。
# 函数签名与命名
- 返回 1 个值,或 2 个值(第二个须为
error类型);返回error时执行失败会透传至Failure分支。 - 函数名须为合法的 Go 标识符,首字母大小写均可(内置
escape即小写)。 TemplateFunc是进程级全局注册表,注册的函数对所有text/template节点共享,暂不支持按节点独立配置函数集。
在 GitHub 上编辑此页 (opens new window)
上次更新: 2026/07/16, 02:02:13