簡體   English   中英

具有多個結構的golang模板

[英]golang template with multiple structs

我有JSON字段這樣的結構:

detail:=&Detail {名稱字符串Detail json.RawMessage}

模板如下所示:

詳細信息= At {{Name}} {{CreatedAt}} {{UpdatedAt}}

我的問題是我們可以對一個模板使用一個或多個結構,還是只限於一個結構。

您可以傳遞任意多的內容。 您沒有提供很多示例可以使用,因此我將假設一些事情,但是您可以通過以下方法解決它:

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

希望能澄清。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM