1 回答

TA貢獻1909條經(jīng)驗 獲得超7個贊
看起來你想要Go Template包。
以下是您如何使用它的示例:定義一個處理程序,將具有某些已定義字段的結構實例傳遞給使用 Go 模板的視圖:
type MyStruct struct {
? ? ? ? SomeField string
}
func MyStructHandler(w http.ResponseWriter, r *http.Request) {
? ? ? ? ms := MyStruct{
? ? ? ? ? ? ? ? SomeField: "Hello Friends",
? ? ? ? }
? ? ? ? t := template.Must(template.ParseFiles("./showmystruct.html"))
t.Execute(w, ms)
}
在您的視圖 (showmystruct.html) 中使用 Go Template 語法訪問結構字段:
<!DOCTYPE html>
<title>Show My Struct</title>
<h1>{{ .SomeField }}</h1>
更新
如果您對傳遞列表并對其進行迭代特別感興趣,那么該{{ range }}關鍵字很有用。此外,還有一種非常常見的模式(至少在我的世界中),您可以將PageData{}結構傳遞給視圖。
這是一個擴展示例,添加了一個結構列表和一個PageData結構(因此我們可以在模板中訪問它的字段):
type MyStruct struct {
? ? SomeField string
}
type PageData struct {
? ? Title string
? ? Data []MyStruct
}
func MyStructHandler(w http.ResponseWriter, r *http.Request) {
? ? ? ? data := PageData{
? ? ? ? ? ? Title: "My Super Awesome Page of Structs",
? ? ? ? ? ? Data: []MyStruct{
? ? ? ? ? ? ? ? MyStruct{
? ? ? ? ? ? ? ? ? ? SomeField: "Hello Friends",
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? MyStruct{
? ? ? ? ? ? ? ? ? ? SomeField: "Goodbye Friends",
? ? ? ? ? ? ? ? },
? ? ? ? ? ? }
? ? ? ? t := template.Must(template.ParseFiles("./showmystruct.html"))
? ? ? ? t.Execute(w, data)
}
以及修改后的模板 (showmystruct.html):
<!DOCTYPE html>
<title>{{ .Title }}</title>
<ul>
? {{ range .Data }}
? ? <li>{{ .SomeField }}</li>
? {{ end }}
</ul>
- 1 回答
- 0 關注
- 114 瀏覽
添加回答
舉報