为了账号安全,请及时绑定邮箱和手机立即绑定

模板不渲染任何内容,也没有错误,但状态为 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 关注
  • 79 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信