Golang 模板函数 returns 空白页

Golang template function returns blank page

我正在尝试更改 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 version 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, and ParseGlob 的实现方式,这会导致您显式传递给 New 的名称与这两种方法分配给已解析模板的名称不一致。

您可以通过调用 DefinedTemplates 方法进行测试。

https://play.golang.org/p/LEi-xSn4LOF


另请查看@icza 的 以更好地了解模板。

经过一些研究和讨论,我猜这条线格式不正确:

tmpl, err := template.New(pageFile).ParseFiles(pageFile)

您不需要New(pageFile)。您只需要直接使用 ParseFiles 方法并记住模板的名称将等于传递文件的基本名称。

所以,稍微接触一下代码并使用:

tmpl, err := template.ParseFiles(pageFile)

查看this example了解更多

func indexHandler(w http.ResponseWriter, r *http.Request) {
  pageFile := "html/testpage.html"
  name := "testpage"
  tmpl, err := template.New(name).Delims("[[", "]]").ParseFiles(pageFile)  //only translate a "name" to New()
  //tmpl := template.Must(template.ParseFiles(pageFile))
  if (err!=nil){
    fmt.Println("Error")
    fmt.Println(err)
  }

  tmpl.Execute(w, nil)
  //tmpl.ExecuteTemplate(w, name, nil)
}