templates - 模板不呈现任何内容,也没有错误,但状态为 200
问题描述
我在一个简单的 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 "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.
如果您的目标是在所有页面中都有一个“固定”的页眉和页脚,那么您必须重新构建您的模板。在某处定义了一个header
和模板,页面应该将它们作为第一个和最后一个元素包含在内。footer
请参阅如何使用结构或变量值的字段作为模板名称?
推荐阅读
- python - Python 3 接受用户输入以访问另一个文件中的字典
- build - 部署到 HockeyApp 时如何使用 Bitrise 构建消息
- haskell - Haskell:包含其他数据类型的数据类型
- angular - 如何在角度将字符串转换为日期对象时忽略时间戳
- php - Google+ Api 已弃用,laravel 5.1 的解决方案
- java - JUnit 测试异常测试得到 Null Exception 而不是 Input Exception
- elasticsearch - 无法为 Cassandra 键空间创建 Elasticsearch 映射
- java - 在 3x3 数组中查找元素
- python - Python3:用于 Android 测试的 Uiautomator 包装器
- php - 在 Laravel 中使用 Vue 组件