go - 无法使用 Go 的“文本/模板”库导入变量
问题描述
我有以下模板文件:
// 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.
但是,当我在删除第 3 行后运行 main 时main.tmpl
,输出为:
This is the main.
Hello
问:为什么调用一个变量helper.tmpl
会导致覆盖This is the main.
,并忽略其余的执行main.tmpl
?似乎缓冲区被覆盖了。这是一个错误吗?
提前致谢。
解决方案
https://golang.org/pkg/text/template/#hdr-Variables
变量的范围扩展到声明它的控制结构(“if”、“with”或“range”)的“结束”操作,如果没有这样的控制结构,则扩展到模板的末尾。模板调用不会从其调用点继承变量。
推荐阅读
- python - 将连续的 SpcCy 实体提取到 Dataframe 中
- node.js - Jenkins Build Execute Shell - 文件权限被拒绝
- python - 为什么打印的 Inline::Python 函数重定向失败?
- c++ - 如何使用 for 循环在 C++ 中打印最少的数字?
- vb.net - 在区域设置更改时格式化 DateTimePicker 中的时间
- java - 如何更改textView文本然后等待然后再次更改多次
- http - 如何使用 Go/WASM 获取所有标头和 cookie
- excel - Excel CountIfs 与日期或条件
- php - 如何在命名空间环境中访问 SimpleXML 节点?
- c - 计算带参数的单词,fgets(),strncmp()