我正在試驗這個包。我也已經管理了例如頁眉,頁腳,導航欄等包含在基本模板中:http/template{{ define "base" }} <!DOCTYPE html> <html> <!-- Start Head --> <head> {{ template "head" }} </head> <!-- End Head --> <!-- Start Body --> <body> {{ template "navbar" }} {{ template "content" }} {{ template "footer" }} </body> <!-- End Body --> </html>{{ end }}404 頁:{{ define "content" }} [...] <h1 class="text-light text-right">404</h1> <small>{{.CurrentURL}}</small> [...]{{ end }}因此,此處的變量應替換為當前 URL。但是,這僅在網站上顯示為空 ():CurrentURL""<small></small>但現在我想替換一個變量,它在網頁上僅顯示為“”。Go 代碼: 解析器:func (parser *TemplateParser) ParseTemplate(name string) (tpl *template.Template, err error) { root, err := template.New("root").Parse(rootTmpl) // ... return root.ParseFiles(files...)}路線:func (ws *WebServer) Exec(name string, r *http.Request, w http.ResponseWriter, data map[string]interface{}) (err error) { // ... // add default data data["CurrentURL"] = r.URL.RequestURI() // ... return tpl.Execute(w, data)}即使使用數組,我也不能使用等:range type Test struct { CurrentURL string C []string } t := Test{ CurrentURL: "Current URL", C: []string {"C1", "c2", "ccc4"}, } tpl.Execute(w, t) <ul>{{range .C}} <li>{{.}}</li>{{end}}</ul><!-- No <li></li> is created -->我做錯了什么?
2 回答

白衣非少年
TA貢獻1155條經驗 獲得超0個贊
您不會將任何數據傳遞給子模板。根據文檔:
{{template "name"}}
The template with the specified name is executed with nil data.
{{template "name" pipeline}}
The template with the specified name is executed with dot set
to the value of the pipeline.
- 2 回答
- 0 關注
- 91 瀏覽
添加回答
舉報
0/150
提交
取消