golang template with multiple structs

huangapple go评论74阅读模式
英文:

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(&amp;detail)
    
    user := User{}
    populateUser(&amp;user)

    // Get a session, set headers, etc.

    // Assuming tmpl is already a defined *template.Template
    tmpl.RenderTemplate(w, &quot;index.tmpl&quot;, M{
        // We can pass as many things as we like
        &quot;detail&quot;: detail,
        &quot;profile&quot;: user,
        &quot;status&quot;: &quot;&quot;, // Just an example
    }
}

... and our template:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;body&gt;
    // Using &quot;with&quot;
    {{ with .detail }}
        {{ .Name }}
        {{ .CreatedAt }}
        {{ .UpdatedAt }}
    {{ end }}

    // ... or the fully-qualified way
    // User has fields &quot;Name&quot;, &quot;Email&quot;, &quot;Address&quot;. We&#39;ll use just two.
    Hi there, {{ .profile.Name }}!
    Logged in as {{ .profile.Email }}
&lt;/body&gt;
&lt;/html&gt;

Hope that clarifies.

huangapple
  • 本文由 发表于 2014年8月15日 23:48:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/25329647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定