【发布时间】:2020-08-28 05:06:04
【问题描述】:
我想从当前的 tmpl 文件创建一个 yaml 文件。基本上我想在/templates 文件夹中存储的sample.tmpl 文件中插入值,并在同一文件夹sample.yml 中创建一个新的yaml 文件
我的sample.tmpl 看起来像
url : {{ .host }}
namespace: {{ .namespace }}
我正在使用以下功能:
func ApplyTemplate(filePath string) (err error) {
// Variables - host, namespace
type Eingest struct {
host string
namespace string
}
ei := Eingest{host: "example.com", namespace: "finance"}
var templates *template.Template
var allFiles []string
files, err := ioutil.ReadDir(filePath)
if err != nil {
fmt.Println(err)
}
for _, file := range files {
filename := file.Name()
fullPath := filePath + "/" + filename
if strings.HasSuffix(filename, ".tmpl") {
allFiles = append(allFiles, fullPath)
}
}
fmt.Println("Files in path: ", allFiles)
// parses all .tmpl files in the 'templates' folder
templates, err = template.ParseFiles(allFiles...)
if err != nil {
fmt.Println(err)
}
s1 := templates.Lookup("sample.tmpl")
s1.ExecuteTemplate(os.Stdout, "sample.yml", ei)
fmt.Println()
return
}
s1.ExecuteTemplate() 写信给stdout。如何在同一文件夹中创建新文件?我相信类似的东西被用来构建 kubernetes yaml 文件。我们如何使用 golang 模板包来实现这一点?
【问题讨论】:
-
如果 yaml 是个好主意,golang stdlib 中会有一个 yaml 包。请不要使用 yaml。从不。
-
最聪明的地鼠。
标签: go go-templates