无法使用 Go 的 "text/template" 库导入变量
Unable to Import Variables using Go's "text/template" Library
我有以下模板文件:
// 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 -}}
并在 Go playground;
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.
然而,当我 运行 my main after delete line 3 in main.tmpl
时,输出是:
This is the main.
Hello
问:为什么从 helper.tmpl
调用变量会覆盖 This is the main.
,并忽略 main.tmpl
的其余部分?缓冲区似乎正在被覆盖。这是一个错误吗?
提前致谢。
https://golang.org/pkg/text/template/#hdr-Variables
A variable's scope extends to the "end" action of the control
structure ("if", "with", or "range") in which it is declared, or to
the end of the template if there is no such control structure. A
template invocation does not inherit variables from the point of its
invocation.
我有以下模板文件:
// 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 -}}
并在 Go playground;
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.
然而,当我 运行 my main after delete line 3 in main.tmpl
时,输出是:
This is the main.
Hello
问:为什么从 helper.tmpl
调用变量会覆盖 This is the main.
,并忽略 main.tmpl
的其余部分?缓冲区似乎正在被覆盖。这是一个错误吗?
提前致谢。
https://golang.org/pkg/text/template/#hdr-Variables
A variable's scope extends to the "end" action of the control structure ("if", "with", or "range") in which it is declared, or to the end of the template if there is no such control structure. A template invocation does not inherit variables from the point of its invocation.