如何在一个文件中运行多个匿名结构体?

huangapple go评论79阅读模式
英文:

How to run multiple anonymous struct in one file?

问题

我有一个匿名结构体,在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)

当我运行代码时,它会运行第一个结构体,但当账户未创建时,它不会运行第二个结构体。

英文:

I have an anonymous struct with the usage in an HTML template like this

sm := struct { Success string } {Success: "Your account is successfully created"}
tmpl.Execute(w, "signup.html", sm)

But then I have another struct with the usage in the same HTML template

fm := struct { Failure string } {Failure: "An account is not created")
tmpl.Execute(w, "signup.html", fm)

When I run the code, it runs the first struct but when the account is not created, it does run the second struct.

答案1

得分: 2

你可以使用简单的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合并为一个.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)
英文:

You can use a simple if statement to accomplish this.

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)
}

Noted that you might want to alter your template html a bit to combine .Success and .Failure into one .Message, so that you can do this:

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)

huangapple
  • 本文由 发表于 2021年8月10日 17:10:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/68724013.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定