英文:
golang template with multiple structs
问题
我有一个包含JSON字段的结构体,类似于这样:
detail := &Detail{
Name string
Detail json.RawMessage
}
模板看起来像这样:
detail = 在{{Name}} {{CreatedAt}} {{UpdatedAt}}
我的问题是,我们可以在一个模板中使用一个或多个结构体,还是只能限制在一个结构体中使用?
英文:
I have struct that has JSON field something like this:
detail := &Detail{
Name string
Detail json.RawMessage
}
template looks like this:
detail = At {{Name}} {{CreatedAt}} {{UpdatedAt}}
My question can we use one or more structs for a single template or it is restricted to only one struct.
答案1
得分: 6
你可以传递任意数量的内容。由于你没有提供太多的示例供我参考,所以我会做一些假设,但是下面是处理的方法:
// 简写 - 很有用!
type M map[string]interface{}
func SomeHandler(w http.ResponseWriter, r *http.Request) {
detail := Detail{}
// 从数据库、API响应等获取
populateDetail(&detail)
user := User{}
populateUser(&user)
// 获取会话,设置头部等
// 假设tmpl已经是一个已定义的*template.Template
tmpl.RenderTemplate(w, "index.tmpl", M{
// 我们可以传递任意数量的内容
"detail": detail,
"profile": user,
"status": "", // 仅作为示例
})
}
... 还有我们的模板:
<!DOCTYPE html>
<html>
<body>
// 使用 "with"
{{ with .detail }}
{{ .Name }}
{{ .CreatedAt }}
{{ .UpdatedAt }}
{{ end }}
// ... 或者完全限定的方式
// User有字段 "Name"、"Email"、"Address"。我们只使用两个。
你好,{{ .profile.Name }}!
登录邮箱为 {{ .profile.Email }}
</body>
</html>
希望能够解答你的问题。
英文:
You can pass as many things as you like. You haven't provided much of an example to work with, so I'm going to assume a few things, but here's how you would tackle it:
// Shorthand - useful!
type M map[string]interface
func SomeHandler(w http.ResponseWriter, r *http.Request) {
detail := Detail{}
// From a DB, or API response, etc.
populateDetail(&detail)
user := User{}
populateUser(&user)
// Get a session, set headers, etc.
// Assuming tmpl is already a defined *template.Template
tmpl.RenderTemplate(w, "index.tmpl", M{
// We can pass as many things as we like
"detail": detail,
"profile": user,
"status": "", // Just an example
}
}
... and our template:
<!DOCTYPE html>
<html>
<body>
// Using "with"
{{ with .detail }}
{{ .Name }}
{{ .CreatedAt }}
{{ .UpdatedAt }}
{{ end }}
// ... or the fully-qualified way
// User has fields "Name", "Email", "Address". We'll use just two.
Hi there, {{ .profile.Name }}!
Logged in as {{ .profile.Email }}
</body>
</html>
Hope that clarifies.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论