具有多个结构的golang模板

时间:2014-08-15 15:48:18

标签: json templates go

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

detail:=& Detail {  名称字符串  细节json.RawMessage }

模板如下所示:

detail = At {{Name}} {{CreatedAt}} {{UpdatedAt}}

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

1 个答案:

答案 0 :(得分:1)

你可以传递任意数量的东西。你没有提供很多可以合作的例子,所以我会假设一些事情,但是你可以解决这个问题:

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

希望澄清。