【问题标题】:golang template with multiple structs具有多个结构的 golang 模板
【发布时间】:2014-08-15 15:48:17
【问题描述】:

我的结构体有这样的 JSON 字段:

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

模板如下所示:

详细信息 = At {{Name}} {{CreatedAt}} {{UpdatedAt}}

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

【问题讨论】:

  • Detail 是一个结构体,它包含一个 Name 字符串和 json.RawMessage 这是一堆字节。您的模板提到 CreatedAt 和 UpdatedAt。如果您的目标是从 json.RawMessage 中提取字段并将它们放入模板中,那么有很多方法可以做到这一点。你能澄清你的问题吗?
  • 是的,我想从 json 中提取字段并将它们添加到同一个模板中。还有我的问题,有没有一种方法可以为一个模板处理多个结构?
  • AFAIK 您只能为您的模板传入一个“对象”,但该对象可以是,例如,您想要的任何类型的结构数组。 HTH。
  • 你能提供一个有效的 playgroud sn-p 你想做什么?
  • 我最初有多个结构用于模板,但我将这些结构嵌入到一个结构中,这解决了我的问题

标签: json templates go


【解决方案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>

希望澄清。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2013-07-16
    • 1970-01-01
    相关资源
    最近更新 更多