【发布时间】:2021-06-03 05:16:28
【问题描述】:
我有以下模板文件:
// main.tmpl
This is the main. // line 1
{{ template "myFunc" }} // line 2
{{- $name }} // line 3
// helper.tmpl
This is a helper
{{- $name := "Nick" -}}
{{- define "myFunc" -}}
Hello
{{- end -}}
package main
import (
"text/template"
"io/ioutil"
"fmt"
"bytes"
)
func main() {
files := []string{"helper.tmpl", "main.tmpl"}
t := template.New(files[0]).Funcs(make(map[string]interface{}))
// Read the contents of each file, and parse it.
// Couldn't get template.ParseFiles working, kept getting
// "incomplete or empty template" errors.
for _, file := range files {
f, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err.Error())
}
t.Parse(string(f))
if err != nil {
fmt.Println(err.Error())
}
}
var buf bytes.Buffer
err := t.Execute(&buf, make(map[string]string))
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(buf.String())
}
当我运行我的主程序时,保持 main.tmpl 不变,输出是:
This is a helper.
但是,当我在删除main.tmpl 中的第 3 行后运行我的 main 时,输出是:
This is the main.
Hello
问:为什么从helper.tmpl 调用变量会导致This is the main. 被覆盖,并忽略main.tmpl 的其余部分?似乎缓冲区正在被覆盖。这是一个错误吗?
提前致谢。
【问题讨论】:
-
您的“手动”解析也可能失败。
t.Parse(string(f))返回一个您没有分配给err的错误,您只需“重新检查”通过读取文件返回的error。 -
另请注意,如果
$name定义在helper.tmpl中,则无法从main.tmpl访问它。 -
@icza 很好地抓住了缺少的
err分配,我什至没有意识到这一点。
标签: go go-templates