doubaran2438 2017-06-16 06:39
浏览 80

如何在文本/模板中和/或文本/模板中发生短路

I have this Go template:

{{ if and $b.Trigger $b.Trigger.Name }} 
  Name is {{ $b.Trigger.Name }}.
{{ else }}
  ...other stuff...
{{ end }}

I'm trying to get this template to do:

if b.Trigger != nil && $b.Trigger.Name != "" { ...

however it doesn't work, because as text/template godoc says, both arguments to and/or functions are evaluated.

When the $b.Trigger.Name is evaluated, it errors out because $b.Trigger can be nil. So it returns error:

template: builds.html:24:46: executing "content" at <$b.Trigger.Name>: can't evaluate field Name in type *myType

I tried refactoring this to:

{{ if and (ne $b.Trigger nil) (ne $b.Trigger.Name "") }}

and weird enough, this fails as well, it says I can't compare $b.Trigger with nil, which doesn't make sense because that field is a pointer type:

template: builds.html:24:31: executing "content" at <ne $b.Trigger nil>: error calling ne: invalid type for comparison

Any ideas?

  • 写回答

1条回答 默认 最新

  • dongmei2351 2019-05-01 04:06
    关注

    As Volker noted above, nest the ifs:

    {{if $b.Trigger}}{{if $b.Trigger.Name}}
      Name is {{ $b.Trigger.Name }}.
    {{end}}{{end}}
    

    Or, more succinctly:

    {{with $b.Trigger}}{{with .Name}}
      Name is {{.}}.
    {{end}}{{end}}
    

    Unfortunately, the above won't handle else clauses. Here's one (rather ugly) possibility:

    {{$bTriggerName := ""}}
    {{with $b.Trigger}}{{$bTriggerName = .Name}}{{end}}
    {{with $bTriggerName}}
      Name is {{.}}.
    {{else}}
      ...other stuff...
    {{end}}
    

    I looked to see if gobuffalo/plush could do this more elegantly, but as of 2019-04-30 it cannot.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?