使用Anonymous Structs将数据传递给GoLang中的模板

原文来自:http://julianyap.com/2013/09/23/using-anonymous-structs-to-pass-data-to-templates-in-golang.html

与Django,Flask或Bottle等Python Web框架相似的一件事是将多个对象传递给视图。

在Django中这样的东西很常见,其中具有多个对象的上下文字典被传递回模板以进行渲染:

from django.shortcuts import render

def my_view(request):
        context = {'poll': p, 'error_message': "You didn't select a choice.",}
        return render(request, 'polls/detail.html', context)

阅读GoLang中的一些示例似乎很奇怪,所有教程和示例只将一个对象传递回模板。

这是一个例子:

package main

import (
    "html/template"
    "net/http"
    "strings"
)

type Paste struct {
    Expiration string
    Content    []byte
    UUID       string
}

func pasteHandler(w http.ResponseWriter, r *http.Request) {
    paste_id := strings.TrimPrefix(r.URL.Path, "/paste")
    paste := &Paste{UUID: paste_id}

    data := paste
    t, _ := template.ParseFiles("templates/paste.html")
    t.Execute(w, data)
}

您的模板代码将如下所示:

Expiration: {{ .Expiration }}
UUID: {{ .UUID }}

如果我们想将多个对象传递给模板怎么办?

我发现一个非常干净的解决方案是使用匿名结构

在下面的示例中,我们现在修改上面示例中的pasteHandler函数,以将额外的布尔标志传递给模板。

func pasteHandler(w http.ResponseWriter, r *http.Request) {
    paste_id := strings.TrimPrefix(r.URL.Path, "/paste")
    paste := &Paste{UUID: paste_id}
    keep_alive := false
    burn_after_reading := false

    data := struct {
        Paste *Paste
        KeepAlive bool
        BurnAfterReading bool
    } {
        paste,
        keep_alive,
        burn_after_reading,
    }
    t, _ := template.ParseFiles("templates/paste.html")
    t.Execute(w, data)
}

然后我们需要修改模板代码来访问这样的对象:

Expiration: {{ .Paste.Expiration }}
UUID: {{ .Paste.UUID}}
{{ if .BurnAfterReading }}
BurnAfterReading: True
{{ else }}
BurnAfterReading: False

猜你喜欢

转载自blog.csdn.net/cbmljs/article/details/87342330