首页 >后端开发 >Golang >Go 模板 if 条件

Go 模板 if 条件

王林
王林转载
2024-02-06 11:24:13420浏览

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删除