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

标签 go go-templates

我有一个简单的 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.

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

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

关于go - 尝试呈现模板,出现错误 html/template : "templates/index.html" is undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51434103/

相关文章:

mysql - golang Gorp 与 SELECT 错误

sql-server-2008 - sql/db 事务没有使用 ms sql 正确回滚

optimization - 如何优化在runtime.osyield和runtime.usleep中花费最多时间的golang程序

string - 在字符串上使用范围时发生类型不一致

go - 模板中的 Nil 指针求值...为什么?有更好的策略吗?

提供静态文件时出现 golang 错误

javascript - 将结构数组传递给HTML模板以填充下拉列表

go - 如何重定向到一个网址

go - 在同一行写入值

html - 随机数未呈现的HTML模板