如何将 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中文网其他相关文章!