如何將 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中文網其他相關文章!