1 回答

TA貢獻1860條經(jīng)驗 獲得超9個贊
Go 的 glob 不支持匹配子目錄中的文件,即**不支持。
您可以使用第三方庫(github 上有許多實現(xiàn)),也可以filepath.Glob為子目錄的每個“級別”調(diào)用并將返回的文件名聚合到單個切片中,然后將切片傳遞給template.ParseFiles:
dirs := []string{
"templates/*.html",
"templates/*/*.html",
"templates/*/*/*.html",
// ...
}
files := []string{}
for _, dir := range dirs {
ff, err := filepath.Glob(dir)
if err != nil {
panic(err)
}
files = append(files, ff...)
}
t, err := template.ParseFiles(files...)
if err != nil {
panic(err)
}
// ...
您還需要記住如何ParseFiles工作:(強調(diào)我的)
ParseFiles 創(chuàng)建一個新模板并從命名文件中解析模板定義。返回的模板名稱將包含第一個文件的(基本)名稱和(解析的)內(nèi)容。必須至少有一個文件。如果發(fā)生錯誤,解析停止并且返回的 *Template 為 nil。
當解析不同目錄中的多個同名文件時,最后提到的將是結(jié)果。例如, ParseFiles("a/foo", "b/foo") 將 "b/foo" 存儲為名為 "foo" 的模板,而 "a/foo" 不可用。
這意味著,如果要加載所有文件,則必須至少確保以下兩件事之一:(1)每個文件的基本名稱在所有模板文件中都是唯一的,而不僅僅是在文件所在的目錄中,或 (2) 通過使用文件內(nèi)容頂部的操作為每個文件提供唯一的模板名稱{{ define "<template_name>" }}(并且不要忘記{{ end }}關(guān)閉define操作)。
作為第二種方法的示例,假設在您的模板中,您有兩個具有相同基本名稱的文件,例如templates/foo/header.html,templates/bar/header.html它們的內(nèi)容如下:
templates/foo/header.html
<head><title>Foo Site</title></head>
templates/bar/header.html
<head><title>Bar Site</title></head>
現(xiàn)在給這些文件一個唯一的模板名稱,您可以將內(nèi)容更改為:
templates/foo/header.html
{{ define "foo/header" }}
<head><title>Foo Site</title></head>
{{ end }}
templates/bar/header.html
{{ define "bar/header" }}
<head><title>Bar Site</title></head>
{{ end }}
完成此操作后,您可以使用 直接執(zhí)行它們,也可以t.ExecuteTemplate(w, "foo/header", nil)通過使用操作讓其他模板引用它們來間接執(zhí)行它們{{ template "bar/header" . }}。
- 1 回答
- 0 關(guān)注
- 124 瀏覽
添加回答
舉報