go - 如何在一个文件中运行多个匿名结构?
问题描述
我有一个匿名结构,在这样的 HTML 模板中使用
sm := struct { Success string } {Success: "Your account is successfully created"}
tmpl.Execute(w, "signup.html", sm)
但后来我在同一个 HTML 模板中使用了另一个结构
fm := struct { Failure string } {Failure: "An account is not created")
tmpl.Execute(w, "signup.html", fm)
当我运行代码时,它运行第一个struct
,但是当没有创建帐户时,它运行第二个struct
。
解决方案
您可以使用简单的 if 语句来完成此操作。
err := whateverYouUseToCreateAccount()
if err != nil {
sm := struct { Success string } {Success: "Your account is successfully created"}
tmpl.Execute(w, "signup.html", sm)
} else {
fm := struct { Failure string } {Failure: "An account is not created")
tmpl.Execute(w, "signup.html", fm)
}
请注意,您可能需要稍微更改模板 html 以将其合并.Success
为.Failure
one .Message
,以便您可以执行以下操作:
type SignupResponse struct { Message string }
err := whateverYouUseToCreateAccount()
var sr SignupResponse
if err != nil {
sr = SignupResponse{ Message: "Your account is successfully created"}
} else {
sr = SignupResponse{ Message: "An account is not created")
}
tmpl.Execute(w, "signup.html", sr)
推荐阅读
- rest - ActiveMQ Artemis REST 集成抛出异常
- python - 我得到'ValueError:没有为任何变量提供渐变:'
- design-patterns - 装饰器与责任链 DP
- functional-programming - 函数式编程原则与函数式编程范式?
- mysql - 如何在SELECT字段中同时使用distinct、count和sum?
- android - 在我的联系人列表中自动保存联系人
- php - 如何显示图像名称字符串中的第一个图像名称
- aws-elasticsearch - 更新 AWS Elasticsearch 集群设置
- r - 保持从 fread 丢弃的行
- haskell - Haskell 多参数类(模板类型类)