
如何将 and 和 eq/ne 函数组合在一起?
我写了这个片段
{{ define "opsgenie.default.tmpl" }}
<font size="+0"><b>{{.commonlabels.alertname }}</b></font>
{{- range $i, $alert := .alerts }}
<font size="+0">{{ .annotations.description }}</font>
{{- end -}}
{{- "\n" -}}
{{- "\n" -}}
{{- if and eq .commonlabels.infoalert "true" eq .commonlabels.topic "database" -}}
grafana: https://{{ .commonlabels.url }}
{{- "\n" -}}{{- end -}}
{{- if and ne .commonlabels.infoalert "true" eq .commonlabels.topic "database" -}}
database:
• https://{{ .commonlabels.url }}/
• https://{{ .commonlabels.url }}/
{{- "\n" -}}{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}目标是:
infoalert: true 和 topic:database 则仅显示 grafana 链接topic: database 但不包含 infoalert: true 则仅显示 databsse 链接它看起来像条件 {{- if and eq .commonlabels.infoalert "true" eq .commonlabels.topic "database" -}} 的语法不正确,因为我在警报时在alertmanager.log中收到此错误被解雇:
notify retry canceled due to unrecoverable error after 1 attempts: templating error: template: email.tmpl:24:17: executing \"opsgenie.default.tmpl\" at <eq>: wrong number of args for eq: want at least 1 got 0
只需使用括号对表达式进行分组:
{{- if and (eq .commonlabels.infoalert "true") (eq .commonlabels.topic "database") -}}
{{- if and (ne .commonlabels.infoalert "true") (eq .commonlabels.topic "database") -}}查看这个可测试的示例:
func main() {
t := template.must(template.new("").parse(src))
m := map[string]any{
"infoalert": "true",
"topic": "database",
}
if err := t.execute(os.stdout, m); err != nil {
panic(err)
}
fmt.println("second round")
m["infoalert"] = "false"
if err := t.execute(os.stdout, m); err != nil {
panic(err)
}
}
const src = `
{{- if and (eq .infoalert "true") (eq .topic "database") -}}
infoalert is true and topic is database
{{- end -}}
{{- if and (ne .infoalert "true") (eq .topic "database") -}}
infoalert is not true and topic is database
{{ end }}
`这将输出(在 go playground 上尝试):
infoalert is true and topic is database Second round infoalert is NOT true and topic is database
以上就是Go 模板 if 条件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号