Go语言模板与多个结构体的使用

3

我有一个包含JSON字段的结构体,类似于以下内容:

detail := &Detail{ Name string Detail json.RawMessage }

模板看起来像这样:

detail = 在{{Name}} {{CreatedAt}} {{UpdatedAt}}处

我的问题是,我们是否可以使用一个或多个结构体来生成单个模板,或者只能限制为一个结构体。


1
细节是一个结构体,它包含一个Name字符串和json.RawMessage,后者是一堆字节。您的模板提到了CreatedAt和UpdatedAt。如果您的目标是从json.RawMessage中提取字段并将它们放入模板中,有很多方法可以实现。您能否澄清您的问题? - Sean
是的,我希望从JSON中提取字段,并将它们添加到同一模板中。另外,我的问题是,我们是否可以在一个模板中使用多个结构体来进行操作? - Oliver.Oakley
据我所知,您只能为模板传递一个"对象",但该对象可以是任意类型的结构体数组,例如。希望有所帮助。 - rogerdpack
你能提供一个有效的代码片段来说明你想做什么吗? - fabrizioM
我最初为一个模板创建了多个结构体,但是我将这些结构体嵌入到一个单一的结构体中,这解决了我的问题。 - Oliver.Oakley
1个回答

6

您可以传递任意数量的参数。由于您没有提供足够的示例供我参考,所以我将做一些假设,但这是如何处理它的方法:

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

...以及我们的模板:

<!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>

希望这能澄清问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接