Go 试图呈现模板时,出现错误html/template:“;模板/index.html“;是未定义的

Go 试图呈现模板时,出现错误html/template:“;模板/index.html“;是未定义的,go,go-templates,Go,Go Templates,我有一个简单的main.go脚本,可以从文件夹加载模板。该模板如下所示: <html> <head> <title>T2 template</title> </head> <body> hello </body> </html> 我不确定这里出了什么问题 我在浏览器中看到的错误是: “templates/index.html”未定义 医生说: 返回的模板名称将具有第一个文件的(基本)名称和(已

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

<html>
<head>
  <title>T2 template</title>
</head>
<body>
 hello
</body>
</html>
我不确定这里出了什么问题

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

“templates/index.html”未定义

医生说:

返回的模板名称将具有第一个文件的(基本)名称和(已解析)内容

要执行模板,请使用“templates/index.html”的

医生说:

返回的模板名称将具有第一个文件的(基本)名称和(已解析)内容

要执行模板,请使用“templates/index.html”的


好的,如果我有很多文件夹和numeriousindex.html文件,我就不能使用解析文件,对吗?没错。文档中说:当解析不同目录中具有相同名称的多个文件时,最后一个提到的文件将是结果文件。例如,ParseFiles(“a/foo”、“b/foo”)将“b/foo”存储为名为“foo”的模板,而“a/foo”不可用。ParseFiles是一种辅助方法。你可以复制逻辑并命名你想要的模板。好吧,如果我有很多文件夹和无数的index.html文件,我就不能使用解析文件,对吗?没错。文档中说:当解析不同目录中具有相同名称的多个文件时,最后一个提到的文件将是结果文件。例如,ParseFiles(“a/foo”、“b/foo”)将“b/foo”存储为名为“foo”的模板,而“a/foo”不可用。ParseFiles是一种辅助方法。可以复制逻辑并根据需要命名模板。
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)
  }
}
tmpl := "index.html"
err := templates.ExecuteTemplate(w, tmpl, "")