亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

模板變量不能到處解析

模板變量不能到處解析

Go
慕斯王 2022-10-10 19:22:16
我正在使用 Golang 模板構建一個網站,并且需要在頁腳模板中顯示一些文本。它是一個在 header.html 和 index.html 中解析的變量。package mainimport (    "fmt"    "html/template"    "log"    "net/http"    "github.com/gorilla/handlers"    "github.com/gorilla/mux")type Data struct {    Title string    Field1 string    Field2 template.HTML    FooterField string}var tmpl *template.Templatefunc main() {    router := mux.NewRouter()    port := ":8085"    data := Data{}    data.Title = "Title"    data.FooterField = "This text does not appear in the footer template"    router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {        err := tmpl.ExecuteTemplate(w, "index", data)        if err != nil {            http.Error(w, err.Error(), http.StatusInternalServerError)        }    })    var err error    tmpl, err = template.ParseGlob("views/*")    if err != nil {        panic(err.Error())    }    router.PathPrefix("/").HandlerFunc(func(res http.ResponseWriter, req *http.Request) {        http.FileServer(http.Dir("./static/")).ServeHTTP(res, req)    })    fmt.Println("Server running on localhost" + port)    err = http.ListenAndServe(port, handlers.CompressHandler(router))    if err != nil {        log.Fatal(err)    }}在 ./views 我有 header.html{{define "header"}}<!doctype html><html><head><meta charset="utf-8"><title>{{.Title}}</title></head><body><h1>Header template</h1><div>{{.FooterField}}</div>{{end}}索引.html{{define "index"}}{{template "header" . }}<h1>Index template</h1><div>{{.FooterField}}</div>{{template "footer"}}{{end}}頁腳.html{{define "footer"}}<h1>Footer template</h1>Missing FooterField->{{.FooterField}}</body></html>{{end}}最后在瀏覽器中輸出 http://localhost:8085/Header templateThis text does not appear in the footer templateIndex templateThis text does not appear in the footer templateFooter templateMissing FooterField->只需復制和粘貼即可復制此代碼。任何線索我的問題是什么?
查看完整描述

1 回答

?
手掌心

TA貢獻1942條經驗 獲得超3個贊

您沒有將任何內容傳遞給頁腳模板。但是你傳遞.給標題模板,所以你.FooterField只看到那里的值。

將其更改為index.html{{template "footer" . }}


查看完整回答
反對 回復 2022-10-10
  • 1 回答
  • 0 關注
  • 103 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號