问题描述
// 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
的其余部分执行?似乎缓冲区正在被覆盖。这是一个错误吗?
提前致谢。
解决方法
https://golang.org/pkg/text/template/#hdr-Variables
变量的作用域扩展到控件的“结束”动作 声明它的结构(“if”、“with”或“range”),或 模板结束,如果没有这样的控制结构。一种 模板调用不从它的角度继承变量 调用。