dongyuan9149 2018-05-16 16:52
浏览 41
已采纳

Golang模板函数返回空白页

I am trying to change the default delimiters for Golang hml templates and here is the code I am using now:

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)
}

The above code renders a blank page in the browser. It will render properly if I use the commented out code instead of the second line.

Here is the template page source:

<!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>

My go version is: go version go1.10.2 linux/amd64

I run it by go run test.go test.go being in the main package

There is no error message being printed in the browser or the terminal.

What am I missing here?

  • 写回答

3条回答 默认 最新

  • douquanzhan0315 2018-05-16 20:07
    关注

    Since html/template uses text/template underneath, you can often find additional information regarding how templates work in the text/template package.

    From the docs of 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.

    (emphasis mine)


    The problem is caused by the fact that you are passing the template file's path as the name of the template and then calling the ParseFiles method.

    Because of how ParseFiles, and ParseGlob for that matter, are implemented, this causes an inconsistency between the name you explicitly passed to New and the names these two methods assign to the parsed templates.

    You can test this by calling the DefinedTemplates method.

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


    Also please take a look at @icza's Go template name answer to get a better understanding of templates.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线