首頁 >後端開發 >Golang >Go 模板 if 條件

Go 模板 if 條件

王林
王林轉載
2024-02-06 11:24:13497瀏覽

Go 模板 if 条件

問題內容

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

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除