Parsing 如何使用go模板使用FuncMap解析html文件
我使用以下代码来解析html模板。它工作得很好Parsing 如何使用go模板使用FuncMap解析html文件,parsing,templates,dictionary,go,func,Parsing,Templates,Dictionary,Go,Func,我使用以下代码来解析html模板。它工作得很好 func test(w http.ResponseWriter, req *http.Request) { data := struct {A int B int }{A: 2, B: 3} t := template.New("test.html").Funcs(template.FuncMap{"add": add}) t, err := t.ParseFiles("test.html") if err!
func test(w http.ResponseWriter, req *http.Request) {
data := struct {A int B int }{A: 2, B: 3}
t := template.New("test.html").Funcs(template.FuncMap{"add": add})
t, err := t.ParseFiles("test.html")
if err!=nil{
log.Println(err)
}
t.Execute(w, data)
}
func add(a, b int) int {
return a + b
}
和html模板test.html
<html>
<head>
<title></title>
</head>
<body>
<input type="text" value="{{add .A .B}}">
</body>
</html>
谁能告诉我怎么了?或者html/模板包不能这样使用 问题是您的程序(
html/template
包)找不到test.html
文件。当您指定相对路径(您的路径是相对路径)时,它们将解析为当前工作目录
您必须确保html文件/模板位于正确的位置。例如,如果您使用go run…
启动应用程序,相对路径将解析为您所在的文件夹,该文件夹将是工作目录
此相对路径:“/templates/test.html”
将尝试分析当前文件夹的templates
子文件夹中的文件。确保它在那里
另一种选择是使用绝对路径
还有另一个重要注意事项:不要在处理函数中解析模板!它运行以服务于每个传入请求。而是在包init()
函数中解析它们一次
详情如下:
很抱歉这个愚蠢的问题。因为我混合了template.New(名称字符串)和t.ParseFiles(文件名…字符串)的参数。它应该是template.New(文件名字符串)。
t := template.New("./templates/test.html").Funcs(template.FuncMap{"add": add})
t, err := t.ParseFiles("./templates/test.html")