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

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

How to run multiple anonymous struct in one file?

问题

我有一个匿名结构体,在HTML模板中的用法如下:

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

但是我还有另一个结构体,在同一个HTML模板中的用法如下:

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

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

英文:

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

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

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

  1. fm := struct { Failure string } {Failure: "An account is not created")
  2. 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语句来实现这个功能。

  1. err := whateverYouUseToCreateAccount()
  2. if err != nil {
  3. sm := struct { Success string } {Success: "Your account is successfully created"}
  4. tmpl.Execute(w, "signup.html", sm)
  5. } else {
  6. fm := struct { Failure string } {Failure: "An account is not created"}
  7. tmpl.Execute(w, "signup.html", fm)
  8. }

请注意,你可能需要稍微修改你的模板HTML,将.Success.Failure合并为一个.Message,这样你就可以这样做:

  1. type SignupResponse struct { Message string }
  2. err := whateverYouUseToCreateAccount()
  3. var sr SignupResponse
  4. if err != nil {
  5. sr = SignupResponse{ Message: "Your account is successfully created"}
  6. } else {
  7. sr = SignupResponse{ Message: "An account is not created"}
  8. }
  9. tmpl.Execute(w, "signup.html", sr)
英文:

You can use a simple if statement to accomplish this.

  1. err := whateverYouUseToCreateAccount()
  2. if err != nil {
  3. sm := struct { Success string } {Success: "Your account is successfully created"}
  4. tmpl.Execute(w, "signup.html", sm)
  5. } else {
  6. fm := struct { Failure string } {Failure: "An account is not created")
  7. tmpl.Execute(w, "signup.html", fm)
  8. }

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:

  1. type SignupResponse struct { Message string }
  2. err := whateverYouUseToCreateAccount()
  3. var sr SignupResponse
  4. if err != nil {
  5. sr = SignupResponse{ Message: "Your account is successfully created"}
  6. } else {
  7. sr = SignupResponse{ Message: "An account is not created")
  8. }
  9. 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:

确定