创建模板并从文件中解析时出现错误。

huangapple go评论87阅读模式
英文:

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

huangapple
  • 本文由 发表于 2015年9月4日 09:29:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/32388777.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定