Home  >  Article  >  Backend Development  >  Go template if condition

Go template if condition

王林
王林forward
2024-02-06 11:24:13380browse

Go 模板 if 条件

Question content

How to combine the and and eq/ne functions together?

I wrote this fragment

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

The target is:

  • If my alert contains two labels infoalert: true and topic:database then only the grafana link will be shown
  • If my alert only contains the tag topic: database but not infoalert: true then only the databsse link will be shown

It looks like the conditional {{- if and eq .commonlabels.infoalert "true" eq .commonlabels.topic "database" -}} has incorrect syntax because I am getting Getting fired with this error in 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

Correct answer


Just use parentheses to group expressions:

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

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

Check out this testable example:

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

This will output (try it on go playground):

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

The above is the detailed content of Go template if condition. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete