我有这个Go模板:
{{ if and $b.Trigger $b.Trigger.Name }}
Name is {{ $b.Trigger.Name }}.
{{ else }}
...other stuff...
{{ end }}
我正在尝试使用此模板:
if b.Trigger != nil && $b.Trigger.Name != "" { ...
然而它不起作用,因为正如text/template godoc所说,评估和/或函数的两个参数。
评估$b.Trigger.Name
时,错误输出是因为$b.Trigger
可能为零。所以它返回错误:
template: builds.html:24:46: executing "content" at <$b.Trigger.Name>: can't evaluate field Name in type *myType
我尝试将其重构为:
{{ if and (ne $b.Trigger nil) (ne $b.Trigger.Name "") }}
而且很奇怪,这也失败了,它说我无法将$ b.Trigger与nil进行比较,这没有意义,因为该字段是指针类型:
template: builds.html:24:31: executing "content" at <ne $b.Trigger nil>: error calling ne: invalid type for comparison
有什么想法吗?
答案 0 :(得分:0)
如上文Volker所述,嵌套if:
{{if $b.Trigger}}{{if $b.Trigger.Name}}
Name is {{ $b.Trigger.Name }}.
{{end}}{{end}}
或更简洁地说:
{{with $b.Trigger}}{{with .Name}}
Name is {{.}}.
{{end}}{{end}}
不幸的是,以上内容无法处理else子句。这是一种(相当难看)的可能性:
{{$bTriggerName := ""}}
{{with $b.Trigger}}{{$bTriggerName = .Name}}{{end}}
{{with $bTriggerName}}
Name is {{.}}.
{{else}}
...other stuff...
{{end}}
我想看看gobuffalo / plush是否可以更优雅地做到这一点,但是截至2019-04-30,它还不能。
答案 1 :(得分:0)
这里解释了为什么在管道中评估所有参数。 它通过 go 模板函数进行评估 https://golang.org/pkg/text/template/#hdr-Functions