如果我在我的模板文件中指定了一个不存在的模板,则错误不是由 ParseFiles() 而是由 ExecuteTemplate() 检测到的。人们会期望解析来检测任何丢失的模板。在解析期间检测此类错误也可能导致性能改进。{{define "test"}}<html> <head> <title> test </title> </head> <body> <h1> Hello, world!</h1> {{template "doesnotexist"}} </body></html>{{end}}主程序package mainimport ( "html/template" "os" "fmt")func main() { t, err := template.ParseFiles("test.html") if err != nil { fmt.Printf("ParseFiles: %s\n", err) return } err = t.ExecuteTemplate(os.Stdout, "test", nil) if err != nil { fmt.Printf("ExecuteTemplate: %s\n", err) }}10:46:30 $ go run main.go ExecuteTemplate: html/template:test.html:8:19: no such template "doesnotexist"10:46:31 $
1 回答
元芳怎么了
TA贡献1798条经验 获得超7个赞
template.ParseFiles()
不报告丢失的模板,因为通常不是所有的模板都在一个步骤中被解析,并且报告丢失的模板(by template.ParseFiles()
)不允许这样做。
可以使用来自多个来源的多个调用来解析模板。
例如,如果您调用该Template.Parse()
方法或您的模板,您可以向其添加更多模板:
_, err = t.Parse(`{{define "doesnotexist"}}the missing piece{{end}}`)
if err != nil {
fmt.Printf("Parse failed: %v", err)
return
}
上面的代码将添加缺失的部分,您的模板执行将成功并生成输出(在Go Playground上尝试):
<html>
<head>
<title> test </title>
</head>
<body>
<h1> Hello, world!</h1>
the missing piece
</body>
</html>
更进一步,不需要解析和“呈现”所有模板为您提供了优化的可能性。可能存在“普通”用户永远不会使用的管理页面,并且仅当管理员用户启动或使用您的应用程序时才需要。在这种情况下,您可以通过不必解析管理页面(仅当/如果管理员用户使用您的应用程序)来加速启动和相同的内存。
- 1 回答
- 0 关注
- 68 浏览
添加回答
举报
0/150
提交
取消