我正在尝试更改 Golang hml 模板的默认分隔符,这是我现在使用的代码:
func indexHandler(w http.ResponseWriter, r *http.Request) {
pageFile := "html/testpage.html"
tmpl, err := template.New(pageFile).Delims("[[", "]]").ParseFiles(pageFile)
//tmpl := template.Must(template.ParseFiles(pageFile))
if (err!=nil){
fmt.Println("Error")
fmt.Println(err)
}
tmpl.Execute(w, nil)
}
以上代码在浏览器中呈现一个空白页面。如果我使用注释掉的代码而不是第二行,它将正确呈现。
模板页面源码如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 </title>
<meta name="description" content="HTML5">
<meta name="author" content="Test">
</head>
<body>
This is html page
</body>
</html>
我的go版本是:go版本go1.10.2 linux/amd64
我通过 go run test.go
test.go 在主包中运行它
浏览器或终端中没有打印错误信息。
我在这里错过了什么?
最佳答案
由于 html/template
在下面使用了 text/template
,您通常可以在 text/template
包中找到有关模板如何工作的其他信息.
来自 ParseFiles 的文档:
Since the templates created by ParseFiles are named by the base names of the argument files, t should usually have the name of one of the (base) names of the files. If it does not, depending on t's contents before calling ParseFiles, t.Execute may fail. In that case use t.ExecuteTemplate to execute a valid template.
(强调我的)
问题是由于您将模板文件的路径作为模板名称传递,然后调用 ParseFiles
方法造成的。
因为如何ParseFiles
, 和 ParseGlob
就此而言,已实现,这会导致您显式传递给 New
的名称与这两个方法分配给已解析模板的名称不一致。
您可以通过调用 DefinedTemplates
来测试它方法。
https://play.golang.org/p/LEi-xSn4LOF
另请查看@icza 的 Go template name answer更好地理解模板。
关于Golang 模板函数返回空白页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50376252/