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

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

模板不渲染任何內容,也沒有錯誤,但狀態為 200

模板不渲染任何內容,也沒有錯誤,但狀態為 200

Go
米琪卡哇伊 2023-08-07 19:09:41
我正在一個簡單的 HTTP 服務器中使用 Go:// var tpl = template.Must(template.New("").Funcs(template.FuncMap{"isRegistered": isRegistered}).ParseGlob("templates/*")) // functions will be added latervar tpl = template.Must(template.ParseGlob("templates/*"))func contact(w http.ResponseWriter, r *http.Request) {    //// defined templates are: "home.html", "layout", "layout.html", "contact.html", "body"    log.Println("in handler: ", tpl.DefinedTemplates())    err := tpl.ExecuteTemplate(w, "contact.html", nil)    if err != nil {        fmt.Println(err) // no error displayed    }    // fmt.Fprintf((w), "write") - This works fine}func main() {    log.Println("Serving on 8888 port")    http.HandleFunc("/contact", contact)    http.ListenAndServe(":8888", nil)}{{define "layout"}}<!DOCTYPE html><html><head>    <meta charset="UTF-8">    <title>{{.Title}}</title>    <meta name="description" content="{{.Description}}">    <link rel="canonical" href="{{.Canonical}}" /></head><body>{{template "body" .}}</body></html>{{end}}{{define "body"}}<h1>Contact us page</h1><p>    Your name is...</p>{{end}}localhost :8888/contact返回 OK 200 和空正文。我使用了這個例子:https ://stackoverflow.com/a/36643663/2110953但我將來還需要添加模板函數: var tpl = template.Must(template.New("").Funcs(template.FuncMap{"isRegistered": isRegistered}).ParseGlob("templates/*"))
查看完整描述

2 回答

?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

你的contact.html不“渲染”任何東西。它僅定義body模板,但不包含它(執行它)。

要執行模板(模板內),您可以使用該{{template}}操作。要定義執行模板,您可以使用該{{block}}操作。

模板操作:

{{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.


{{block "name" pipeline}} T1 {{end}}

? ? A block is shorthand for defining a template

? ? ? ? {{define "name"}} T1 {{end}}

? ? and then executing it in place

? ? ? ? {{template "name" pipeline}}

? ? The typical use is to define a set of root templates that are

? ? then customized by redefining the block templates within.

如果您的目標是在所有頁面中擁有“固定”頁眉和頁腳,那么您必須重新構建模板。在某處定義了headerfooter模板,并且頁面應將它們作為第一個和最后一個元素包含在內。


查看完整回答
反對 回復 2023-08-07
?
千巷貓影

TA貢獻1829條經驗 獲得超7個贊

更新:所以我不得不創建一個頁眉和頁腳模板:


{{template "header" .}}


<h1>Contact us page</h1>


<p>

    Your name is...

</p>



{{template "footer" .}}

{{define "header"}}

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>{{.Title}}</title>

    <meta name="description" content="{{.Description}}">

    <link rel="canonical" href="{{.Canonical}}" />

</head>

<body>

{{end}}

{{define "footer"}}

</body>

</html>

{{end}}

效果很好


查看完整回答
反對 回復 2023-08-07
  • 2 回答
  • 0 關注
  • 194 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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