首页 > 解决方案 > 如何在一个文件中运行多个匿名结构?

问题描述

我有一个匿名结构,在这样的 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

标签: gostruct

解决方案


您可以使用简单的 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.Failureone .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)

推荐阅读