具有多个结构的golang模板 [英] golang template with multiple structs

查看:57
本文介绍了具有多个结构的golang模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have struct that has JSON field something like this:

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

detail := &Detail{ Name string Detail json.RawMessage }

模板看起来像这样:

细节= 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.

推荐答案

您可以传递任意多的内容.您没有提供很多示例可以使用,因此我将假设一些事情,但是您可以通过以下方法解决它:

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(&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
    }
}

...以及我们的模板:

... and our template:

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

希望如此.

这篇关于具有多个结构的golang模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆