英文:
Error when creating a template and then parsing from files
问题
我不知道我是否犯了一些错误或者遇到了一个golang的bug。以下的代码并不按照我的期望工作,并返回以下错误信息:
- 错误:模板“name”是不完整或空的模板;已定义的模板有:“test.tmpl”
test.go
package main
import (
"log"
"os"
"text/template"
)
func main() {
t1 := template.New("name")
t2 := template.Must(t1.ParseFiles("test.tmpl"))
err := t2.Execute(os.Stdout, nil)
if err != nil {
log.Println("错误:", err)
}
}
test.tmpl
{{ "test ok" }}
英文:
I don't know if I made some mistake or hit a golang's bug. The following code does not work as I expect and returns:
- error: template: name: "name" is an incomplete or empty template; defined templates are: "test.tmpl"
test.go
package main
import (
"log"
"os"
"text/template"
)
func main() {
t1 := template.New("name")
t2 := template.Must(t1.ParseFiles("test.tmpl"))
err := t2.Execute(os.Stdout, nil)
if err != nil {
log.Println("error: ", err)
}
}
test.tmpl
{{"\"test ok\""}}
答案1
得分: 6
我找到了问题。根据包文档,模板通常应该使用文件名之一的名称。
修正后的代码
package main
import (
"log"
"os"
"text/template"
)
func main() {
t1 := template.New("test.tmpl")
t2 := template.Must(t1.ParseFiles("test.tmpl"))
err := t2.Execute(os.Stdout, nil)
if err != nil {
log.Println("错误: ", err)
}
}
英文:
I found the problem. According the package documentation, the template should usually have the name of one of the names of the files.
Corrected code
package main
import (
"log"
"os"
"text/template"
)
func main() {
t1 := template.New("test.tmpl")
t2 := template.Must(t1.ParseFiles("test.tmpl"))
err := t2.Execute(os.Stdout, nil)
if err != nil {
log.Println("error: ", err)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论