Reference for all template functions available in the Nightingale monitoring system, including usage and examples.
This document provides a detailed introduction to all available template functions in the Nightingale monitoring system, including usage and examples.
Table of Contents
- Query Functions
- Formatting Functions
- String Processing Functions
- Time Processing Functions
- Math Operations
- Data Processing Functions
Additional Query Functions
query
Description: Executes a Prometheus query and returns the result. This is a special template function used in alert annotations to dynamically query metric data.
Function signature:
func(promql string, param ...int64) QueryResult
Parameters:
promql: Prometheus query statementparam: optional, specifies the data source ID. If not specified, the data source of the current alert rule is used.
Return value: QueryResult type, containing the sample data of the query result. Each sample contains:
Labels: amap[string]stringset of labelsValue: afloat64numeric value
Examples:
- Query monitoring metrics
{{ $metrics := query "mem_available_percent" }}
{{ range $metrics }}
机器: {{ .Labels.ident }}
内存使用率: {{ .Value }}
{{ end }}
You can use this template function in the alert rule’s annotations to fetch extra information at alert time.

- Query monitoring metrics filtered by a label from the alert event
{{ $memMetrics := query (printf "mem_available_percent{ident=\"%s\"}" .TagsMap.ident) }}
{{ range $memMetrics }}
机器: {{ .Labels.ident }}
内存使用率: {{ .Value }}
{{ end }}
Formatting Functions
humanize
Description: Format a number into a human-readable form using SI prefixes (k, M, G, T, etc.).
Examples:
{{ "1234567" | humanize }} // 输出: 1.23M
{{ "0.00123" | humanize }} // 输出: 1.23m
{{ "1000000000" | humanize }} // 输出: 1.00G
humanize1024
Description: Format a number into a human-readable form using binary prefixes (Ki, Mi, Gi, Ti, etc.).
Examples:
{{ "1048576" | humanize1024 }} // 输出: 1Mi
{{ "1073741824" | humanize1024 }} // 输出: 1Gi
{{ "2048" | humanize1024 }} // 输出: 2ki
humanizeDuration
Description: Convert seconds into a human-readable time format.
Examples:
{{ "3661" | humanizeDuration }} // 输出: 1h 1m 1s
{{ "86400" | humanizeDuration }} // 输出: 1d 0h 0m 0s
{{ "0.5" | humanizeDuration }} // 输出: 500ms
humanizePercentage
Description: Convert a decimal to a percentage format (multiplied by 100).
Examples:
{{ "0.8567" | humanizePercentage }} // 输出: 85.67%
{{ "0.05" | humanizePercentage }} // 输出: 5.00%
{{ "1" | humanizePercentage }} // 输出: 100.00%
humanizePercentageH
Description: Format directly as a percentage (without multiplying by 100).
Examples:
{{ "85.67" | humanizePercentageH }} // 输出: 85.67%
{{ "5" | humanizePercentageH }} // 输出: 5.00%
{{ "100" | humanizePercentageH }} // 输出: 100.00%
formatDecimal
Description: Format a number to a specified number of decimal places.
Examples:
{{ formatDecimal "3.14159" 2 }} // 输出: 3.14
{{ formatDecimal "10.5" 3 }} // 输出: 10.500
{{ formatDecimal "0.123456" 4 }} // 输出: 0.1235
printf
Description: Format an output string, with special optimization for numeric strings (automatically tries to convert a string to a float for formatting).
Function signature:
func Printf(format string, value interface{}) string
Characteristics:
- If a numeric string is passed in, it will be automatically converted to a float for formatting.
- Supports standard Go formatting verbs.
Examples:
// 格式化浮点数(字符串会自动转换)
{{ printf "%.2f" "3.14159" }} // 输出: 3.14
{{ printf "%.2f" .TriggerValue }} // 将触发值格式化为2位小数
// 百分比格式化
{{ printf "%.1f%%" "85.67" }} // 输出: 85.7%
{{ printf "使用率: %.2f%%" .TriggerValue }} // 输出: 使用率: 85.67%
// 科学计数法
{{ printf "%e" "1234567" }} // 输出: 1.234567e+06
{{ printf "%.2e" .TriggerValue }} // 输出: 8.57e+01
// 整数格式化(需要注意类型)
{{ printf "%d" 42 }} // 输出: 42
// 字符串格式化
{{ printf "主机 %s 告警" .TagsMap.hostname }} // 输出: 主机 server01 告警
// 组合使用
{{ printf "[%s] %.2f%% (阈值: %.0f%%)" .RuleName .TriggerValue 80.0 }}
// 输出: [CPU告警] 85.67% (阈值: 80%)
String Processing Functions
escape
Description: URL path escaping.
Examples:
{{ "hello world" | escape }} // 输出: hello%20world
{{ "a/b/c" | escape }} // 输出: a%2Fb%2Fc
unescaped
Description: Output a string as HTML (without escaping).
Examples:
{{ "<b>Bold Text</b>" | unescaped }} // 输出原始HTML: <b>Bold Text</b>
{{ "<script>alert('hi')</script>" | unescaped }} // 输出原始脚本标签
urlconvert
Description: Convert a string to a URL type.
Examples:
{{ "http://example.com" | urlconvert }} // 转换为URL类型
toUpper
Description: Convert to uppercase.
Examples:
{{ "hello world" | toUpper }} // 输出: HELLO WORLD
{{ .TagsMap.env | toUpper }} // 将标签值转为大写
toLower
Description: Convert to lowercase.
Examples:
{{ "HELLO WORLD" | toLower }} // 输出: hello world
{{ .TagsMap.DC | toLower }} // 将标签值转为小写
title
Description: Convert a string to title case (first letter of each word capitalized).
Examples:
{{ "hello world" | title }} // 输出: Hello World
{{ "api_server" | title }} // 输出: Api_Server
contains
Description: Check whether a string contains a substring.
Examples:
{{ if contains "hello world" "world" }}包含{{ end }} // 输出: 包含
{{ if contains .TagsMap.service "api" }}是API服务{{ end }}
match
Description: Regular expression matching.
Examples:
{{ if match "^prod-.*" .TagsMap.env }}生产环境{{ end }}
{{ if match "[0-9]+" "abc123" }}包含数字{{ end }}
reReplaceAll
Description: Regular expression replacement.
Examples:
{{ reReplaceAll "[0-9]+" "X" "abc123def456" }} // 输出: abcXdefX
{{ reReplaceAll "\\s+" "-" "hello world" }} // 输出: hello-world
split
Description: String splitting.
Examples:
{{ split "a,b,c" "," }} // 返回: ["a", "b", "c"]
{{ range .TagsJSON }}
标签: {{ . }}
{{ end }}
join
Description: String joining.
Examples:
{{ join (split "a,b,c" ",") "-" }} // 输出: a-b-c
{{ $arr := args "hello" "world" }}
{{ join $arr " " }} // 输出: hello world
toString
Description: Convert any type to a string.
Examples:
{{ toString 123 }} // 输出: "123"
{{ toString 3.14 }} // 输出: "3.14"
{{ toString .Value }} // 将数值转为字符串
Time Processing Functions
timeformat
Description: Format a Unix timestamp.
Examples:
{{ timeformat 1609459200 }} // 输出: 2021-01-01 00:00:00
{{ timeformat 1609459200 "2006-01-02" }} // 输出: 2021-01-01
{{ timeformat .Timestamp "15:04:05" }} // 输出时间部分
timestamp
Description: Get the formatted string of the current time.
Examples:
{{ timestamp }} // 输出: 2024-01-15 10:30:45
{{ timestamp "2006-01-02" }} // 输出: 2024-01-15
{{ timestamp "15:04:05" }} // 输出: 10:30:45
now
Description: Get the current time object.
Examples:
{{ now }} // 返回当前时间对象
{{ now.Format "2006-01-02" }} // 格式化当前时间
{{ now.Unix }} // 获取Unix时间戳
toTime
Description: Convert a timestamp into a time object.
Examples:
{{ $t := toTime 1609459200 }}
{{ $t.Format "2006-01-02" }} // 输出: 2021-01-01
parseDuration
Description: Parse a duration string.
Examples:
{{ parseDuration "1h30m" }} // 返回: 5400 (秒)
{{ parseDuration "24h" }} // 返回: 86400 (秒)
{{ parseDuration "5m" }} // 返回: 300 (秒)
Math Operations
add
Description: Addition.
Examples:
{{ add 10 20 }} // 输出: 30
sub
Description: Subtraction.
Examples:
{{ sub 100 30 }} // 输出: 70
mul
Description: Multiplication.
Examples:
{{ mul 10 5 }} // 输出: 50
div
Description: Division.
Examples:
{{ div 100 5 }} // 输出: 20
Data Processing Functions
first
Description: Get the first element of a query result.
Function signature:
func(v QueryResult) (*sample, error)
Examples:
{{ $result := query "up" }}
{{ with first $result }}
第一个实例: {{ label "instance" . }} 状态: {{ value . }}
{{ end }}
// 注意:在 AlertCurEvent 上下文中访问标签应使用 TagsMap
第一个触发的主机: {{ .TagsMap.hostname }}
label
Description: Get a label value from a sample in a query result (used with a single sample of the QueryResult returned by the query function).
Function signature:
func(label string, s *sample) string
Examples:
{{ $result := query "up" }}
{{ range $result }}
主机名: {{ label "hostname" . }}
环境: {{ label "env" . }}
{{ end }}
value
Description: Get the numeric value of a sample in a query result (used with a single sample of the QueryResult returned by the query function).
Function signature:
func(s *sample) float64
Examples:
{{ $result := query "cpu_usage" }}
{{ range $result }}
CPU使用率: {{ value . }}%
{{ end }}
Template Rendering Context (AlertCurEvent)
When rendering alert rule annotations and notification templates, the template engine passes the AlertCurEvent object as the context. You can directly access all fields of this object.
Predefined Variables
At the start of the template, the following convenience variables are automatically defined:
$labels: equivalent to.TagsMap, containing all label key-value pairs$value: equivalent to.TriggerValue, the value that triggered the alert$annotations: equivalent to.AnnotationsJSON, annotation key-value pairs (only available in certain scenarios)
Main Fields of AlertCurEvent
| Field | Type | Description | Example |
|---|---|---|---|
.Id |
int64 | Alert event ID | 告警ID: {{ .Id }} |
.Cate |
string | Alert category | 类别: {{ .Cate }} |
.Cluster |
string | Cluster name | 集群: {{ .Cluster }} |
.DatasourceId |
int64 | Data source ID | 数据源: {{ .DatasourceId }} |
.GroupId |
int64 | Business group ID | 业务组ID: {{ .GroupId }} |
.GroupName |
string | Business group name | 业务组: {{ .GroupName }} |
.RuleId |
int64 | Rule ID | 规则ID: {{ .RuleId }} |
.RuleName |
string | Rule name | 规则: {{ .RuleName }} |
.RuleNote |
string | Rule note | 备注: {{ .RuleNote }} |
.RuleProd |
string | Rule product line | 产品线: {{ .RuleProd }} |
.RuleAlgo |
string | Rule algorithm | 算法: {{ .RuleAlgo }} |
.Severity |
int | Alert severity (1-3) | {{ if eq .Severity 1 }}P1级告警{{ end }} |
.PromQl |
string | PromQL query statement | 查询: {{ .PromQl }} |
.PromForDuration |
int | Duration threshold (seconds) | 持续: {{ .PromForDuration }}秒 |
.PromEvalInterval |
int | Evaluation interval (seconds) | 评估间隔: {{ .PromEvalInterval }}秒 |
.RunbookUrl |
string | Runbook URL | <a href="{{ .RunbookUrl }}">运维手册</a> |
.TargetIdent |
string | Target identifier | 目标: {{ .TargetIdent }} |
.TargetNote |
string | Target note | {{ .TargetNote }} |
.TriggerTime |
int64 | Trigger timestamp | {{ .TriggerTime | timeformat }} |
.TriggerValue |
string | Trigger value | 当前值: {{ .TriggerValue }} |
.TagsMap |
map[string]string | Label key-value pairs | 主机: {{ .TagsMap.hostname }} |
.TagsJSON |
[]string | Label array | {{ range .TagsJSON }}{{ . }} {{ end }} |
.AnnotationsJSON |
map[string]string | Annotation key-value pairs | {{ .AnnotationsJSON.description }} |
.NotifyChannels |
[]string | Notification channels | {{ range .NotifyChannelsJSON }}{{ . }}{{ end }} |
.NotifyGroups |
[]string | Notification groups | {{ range .NotifyGroupsJSON }}{{ . }}{{ end }} |
.NotifyCurNumber |
int | Current notification count | 第{{ .NotifyCurNumber }}次通知 |
.FirstTriggerTime |
int64 | First trigger time | 首次告警: {{ .FirstTriggerTime | timeformat }} |
.Claimant |
string | Claimer | 认领人: {{ .Claimant }} |
Usage Examples
// 基础信息访问
告警名称:{{ .RuleName }}
告警级别:{{ if eq .Severity 1 }}P1{{ else if eq .Severity 2 }}P2{{ else }}P3{{ end }}
业务组:{{ .GroupName }}
触发时间:{{ .TriggerTime | timeformat "2006-01-02 15:04:05" }}
当前值:{{ .TriggerValue | humanize }}
// 使用预定义变量
主机名:{{ $labels.ident }}
当前值:{{ $value | humanizePercentage }}
// 条件判断
{{ if gt (toFloat64 .TriggerValue) 80 }}
严重:使用率超过80%
{{ else if gt (toFloat64 .TriggerValue) 60 }}
警告:使用率超过60%
{{ end }}
// 遍历标签
{{ range $k, $v := .TagsMap }}
{{ $k }}: {{ $v }}
{{ end }}
// 访问注解
描述:{{ .AnnotationsJSON.description }}
摘要:{{ .AnnotationsJSON.summary }}
FAQ
Q1: What’s the difference between template functions and Go’s standard template?
A: n9e extends Go’s standard template with alert-scenario-specific functions (time formatting, unit conversion, string processing, JSON parsing, etc.). All extension functions are implemented in tplx.go.
Q2: What should I do if I get an “undefined function” error while debugging a template?
A: Either the function name is misspelled, or you’re using a function that an older version doesn’t support. Check tplx.go for the function name against your n9e Server version.
Q3: Can I define custom template functions?
A: Currently this requires modifying the n9e source code and recompiling. Community-edition approach:
- Add a custom function in
tplx.go; - Register it in
funcMap; - Recompile the server.
Q4: A timestamp appears in the template — how do I convert it to a human-readable form?
A: Use timeformat: {{timeformat .LastEvalTime}} outputs 2026-05-19 15:30:00. For a custom format, use timeformat <field> "2006-01-02 15:04:05" (Go time format).