尝试呈现模板时出现错误 html/template: "templates/index.html" is undefined

Trying to render a template, getting an error html/template: "templates/index.html" is undefined

我有一个简单的 main.go 脚本可以从文件夹加载模板。模板如下所示:

<html>
<head>
  <title>T2 template</title>
</head>
<body>
 hello
</body>
</html>

main.go 脚本看起来是:

package main

import (

  "fmt"
  "html/template"
  "log"
  "net/http"
  "os"

  "github.com/gorilla/mux"
)

var (
  templates = template.Must(template.ParseFiles("templates/index.html"))
)

func main() {

  port := os.Getenv("PORT")

  fmt.Printf("port is: %v\n", port)

  r := mux.NewRouter()

  r.HandleFunc("/hello", HomeHandler)

  log.Fatal(http.ListenAndServe(":"+port, r))
}

func HomeHandler(w http.ResponseWriter, r *http.Request) {
  tmpl := "templates/index.html"

  err := templates.ExecuteTemplate(w, tmpl, "")
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
  }
}

我不确定这里出了什么问题。

我在浏览器中看到的错误是:

"templates/index.html" is undefined

ParseFiles 文档说:

The returned template's name will have the (base) name and (parsed) contents of the first file.

要执行模板,请使用 "templates/index.html" 的 base name

tmpl := "index.html"
err := templates.ExecuteTemplate(w, tmpl, "")