gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:37:17 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com