我是 Go 新手,正在尝试进行一些概念证明。因此,我想将模板文件名传递给 template.ParseFiles
,如下所示:
var Templates = template.Must(template.ParseFiles("views/edit.html", "views/view.html", "views/main.html"))
为了动态地做到这一点,我正在尝试这样做:
func ExtractFileNames () (templateFileNames []string) {
files, _ := ioutil.ReadDir("./views")
for _, f := range files {
if strings.Contains(f.Name(), ".html") {
templateFileNames=append(templateFileNames, "views/" + f.Name())
}
}
return templateFileNames
}
var Templates = template.Must(template.ParseFiles(templateFileNames))
该函数运行正常,只是出现错误:
undefined: templateFileNames
这让人觉得我可能没有使用解决这个问题的最佳方法。
最佳答案
返回变量 - 就像普通参数和方法接收者一样 - 作用域为函数体。
规范中提到:Declarations and Scope:
The scope of an identifier denoting a method receiver, function parameter, or result variable is the function body.
在函数之外,它们不在范围内,您无法引用它们。
在您的情况下,非常简单的解决方法是您必须调用该函数,并且它返回什么,您可以使用它(您可以传递它,将其分配给变量等):
var Templates = template.Must(template.ParseFiles(ExtractFileNames()...))
这里需要注意的一点是称为省略号的...
。这是必需的,因为 ExtractFileNames()
返回一个 slice ,但 template.ParseFiles()
有一个可变参数:
func ParseFiles(filenames ...string) (*Template, error)
这样 ...
将告诉编译器您想要传递“爆炸”切片作为可变参数的值(而不是例如可变参数列表中的单个元素)。 ..)。规范中有关此内容的更多信息:Passing arguments to ... parameters
关于go - 如何使返回变量在函数外部不被定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38732390/