去模板和功能 [英] Go template and function

查看:136
本文介绍了去模板和功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我经常使用如果像这样

 如果用户&& user.Registered {} 

go模板中的等效代码将是

  {{if and .User .User.Registered}} {{end}} 

不幸的是,如果 .User nil ,那么模板中的代码将失败。 / b>

是否有可能在go模板中实现同样的功能?

解决方案

模板函数不会执行短路评估,例如Go && 运算符。



code>和函数在函数被调用之前被求值。即使 .User 为零,表达式 .User.Registered 也总是被计算。



如果使用嵌套

  {{if .User}} {{if .UserRegistered}} {{end}} {{end}} 

通过使用a可以避免嵌套 if 模板函数:

  func isRegistered(u * user)bool {
return u!= nil&& u.Registered
}

const tmpl =`{{if isRegistered .User}} registered {{else}} not registered {{end}}`

t := template.Must(template.New()。Funcs(template.FuncMap {isRegistered:isRegistered})。Parse(tmpl))

游乐场示例


In my go code I often use if like this

if user && user.Registered { }

equivalent code in go templates would be

{{ if and .User .User.Registered }} {{ end }}

Unfortunately code in the template fails, if .User is nil :/

Is it possible to achieve the same thing in go templates?

解决方案

The template and function does not do short circuit evaluation like the Go && operator.

The arguments to the and function are evaluated before the function is called. The expression .User.Registered is always evaluated, even if .User is nil.

The fix is to use nested if:

 {{if .User}}{{if .UserRegistered}}  {{end}}{{end}}

You can avoid the nested if or with by using a template function:

func isRegistered(u *user) bool {
  return u != nil && u.Registered
}

const tmpl = `{{if isRegistered .User}}registered{{else}}not registered{{end}}`

t := template.Must(template.New("").Funcs(template.FuncMap{"isRegistered": isRegistered}).Parse(tmpl))

playground example

这篇关于去模板和功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆