创建模板然后从文件解析时出错

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\""}}

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)
    }
}