Go模板和函数

标签 go go-templates

在我的 go 代码中,我经常像这样使用 if

if user && user.Registered { }

go 模板中的等效代码是

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

不幸的是,如果 .Usernil,模板中的代码将失败:/

是否可以在 go 模板中实现相同的功能?

最佳答案

模板函数不做short circuit像 Go 的 && 运算符一样的评估。

函数的参数在调用函数之前进行计算。表达式 .User.Registered 总是被求值,即使 .User 为 nil。

解决方法是使用嵌套的 if:

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

您可以使用模板函数避免嵌套的 ifwith:

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

关于Go模板和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42208440/

相关文章:

go - 如何遍历请求参数

go - 是否为每个版本隔离或共享了drone.io服务?

firebase - 如何通过RPC监听Firestore

templates - Helm _helpers.tpl : Calling defined templates in other template definitions

go - 在Go中以恒定的时间从文件中读取随机行

安装 go 工具的 go 模块

kubernetes - Helm 图中的点 "."是什么,以及哪些用例?

kubernetes - 如何使用 kubectl 命令从 k8s configmap 中的 yaml 文件中获取值?

go - Gcloud函数部署找不到Golang模板文件

templates - Golang 模板(并将函数传递给模板)