英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论