gpt4 book ai didi

templates - 模板不呈现任何内容,也没有错误,但是状态为200

转载 作者:行者123 更新时间:2023-12-01 22:31:16 24 4
gpt4 key购买 nike

我在一个简单的HTTP服务器上玩Go:

// var tpl = template.Must(template.New("").Funcs(template.FuncMap{"isRegistered": isRegistered}).ParseGlob("templates/*")) // functions will be added later
var 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 lang="en">
<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 / *”))

最佳答案

您的contact.html不“呈现”任何内容。它仅定义body模板,但不包括它(执行它)。

要执行模板(在模板内),可以使用{{template}}操作。要定义和执行模板,可以使用{{block}}操作。

Template Actions:

{{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模板,页面应将它们作为第一个和最后一个元素。参见 How to use a field of struct or variable value as template name?

关于templates - 模板不呈现任何内容,也没有错误,但是状态为200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59194131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com