Heim  >  Artikel  >  Backend-Entwicklung  >  Go-Vorlage, wenn Bedingung

Go-Vorlage, wenn Bedingung

王林
王林nach vorne
2024-02-06 11:24:13379Durchsuche

Go 模板 if 条件

Frageninhalt

Wie kombiniere ich andeq/ne Funktionen miteinander?

Ich habe diesen Clip geschrieben

{{ 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 -}}

Das Ziel ist:

  • Wenn meine Benachrichtigung zwei Labels enthält infoalert: truetopic:database wird nur der Grafana-Link angezeigt
  • Wenn meine Benachrichtigung nur Tags enthält topic: database 但不包含 infoalert: true, wird nur der Datenbanklink angezeigt

Es sieht so aus, als ob die Syntax für die Bedingung {{- if and eq .commonlabels.infoalert "true" eq .commonlabels.topic "database" -}} falsch ist, weil ich diesen Fehler in „alertmanager.log“ erhalte, wenn die Warnung ausgelöst wird:

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

Richtige Antwort


Verwenden Sie einfach Klammern, um Ausdrücke zu gruppieren:

{{- if and (eq .commonlabels.infoalert "true") (eq .commonlabels.topic "database") -}}

{{- if and (ne .commonlabels.infoalert "true") (eq .commonlabels.topic "database") -}}

Schauen Sie sich dieses testbare Beispiel an:

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 }}
`

Dies wird ausgegeben (versuchen Sie es auf Go Playground):

infoalert is true and topic is database
Second round
infoalert is NOT true and topic is database

Das obige ist der detaillierte Inhalt vonGo-Vorlage, wenn Bedingung. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:stackoverflow.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen