具有多个结构的 golang 模板

Oli*_*ley 3 templates json go

我有一个具有 JSON 字段的结构,如下所示:

详细信息 := &Detail{ 名称字符串详细信息 json.RawMessage }

模板看起来像这样:

细节=At {{Name}} {{CreatedAt}} {{UpdatedAt}}

我的问题是我们可以为单个模板使用一个或多个结构,还是仅限于一个结构。

eli*_*rar 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
    }
}
Run Code Online (Sandbox Code Playgroud)

...以及我们的模板:

<!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>
Run Code Online (Sandbox Code Playgroud)

希望能澄清。