问题内容 如何将 and 和 eq/ne 函数组合在一起? 我写了这个片段 {{ define "opsgenie.default.tmpl" }} {{.commonlabels
如何将 and
和 eq/ne
函数组合在一起?
我写了这个片段
{{ define "opsgenie.default.tmpl" }}
{{.commonlabels.alertname }}
{{- range $i, $alert := .alerts }}
{{ .annotations.description }}
{{- 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 : 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 条件的详细内容,更多请关注编程网其它相关文章!
--结束END--
本文标题: Go 模板 if 条件
本文链接: https://lsjlt.com/news/561466.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0