这是我的目录结构:
[root@abc]# ll
drwxr-xr-x. 2 root root 133 Mar 26 16:13 credit
drwxr-xr-x. 2 root root 132 Mar 26 16:17 form
-rw-r--r--. 1 root root 6003 Mar 27 19:30 main.go
var tmpl = template.Must(template.ParseGlob("form/*"))
解析表单目录中的所有文件。如何解析 credit 目录文件?
var tmpl = template.Must(template.ParseGlob("form/*","credit/*"))
不起作用。
答案 0 :(得分:0)
var tmpl = template.Must(template.ParseGlob("*/*"))
快速示例:
目录结构:
-rw-r--r-- 1 User staff 194 Mar 28 07:39 main.go
drwxr-xr-x 3 User staff 102 Mar 28 07:38 test1
drwxr-xr-x 3 User staff 102 Mar 28 07:38 test2
test1的内容
-rw-r--r-- 1 User staff 0 Mar 28 07:38 template1.html
test2的内容
-rw-r--r-- 1 User staff 0 Mar 28 07:38 template2.html
main.go
package main
import (
"fmt"
"html/template"
)
func main() {
var tmpl = template.Must(template.ParseGlob("*/*"))
fmt.Println(tmpl.DefinedTemplates())
}
输出:
; defined templates are: "template2.html", "template1.html"
template.ParseGlob使用filepath.Glob进行通配。
// parseGlob is the implementation of the function and method ParseGlob. (Lines 461-474 of template.go)
func parseGlob(t *Template, pattern string) (*Template, error) {
if err := t.checkCanParse(); err != nil {
return nil, err
}
filenames, err := filepath.Glob(pattern) // <- right here
if err != nil {
return nil, err
}
if len(filenames) == 0 {
return nil, fmt.Errorf("html/template: pattern matches no files: %#q", pattern)
}
return parseFiles(t, filenames...)
}
所以它遵循相同的规则:
// Glob returns the names of all files matching pattern or nil
// if there is no matching file. The syntax of patterns is the same
// as in Match. The pattern may describe hierarchical names such as
// /usr/*/bin/ed (assuming the Separator is '/').
//
// Glob ignores file system errors such as I/O errors reading directories.
// The only possible returned error is ErrBadPattern, when pattern
// is malformed. (Lines 226-233 path/filepath/match.go)
匹配的描述是:
// Match reports whether name matches the shell file name pattern.
// The pattern syntax is:
//
// pattern:
// { term }
// term:
// '*' matches any sequence of non-Separator characters
// '?' matches any single non-Separator character
// '[' [ '^' ] { character-range } ']'
// character class (must be non-empty)
// c matches character c (c != '*', '?', '\\', '[')
// '\\' c matches character c
//
// character-range:
// c matches character c (c != '\\', '-', ']')
// '\\' c matches character c
// lo '-' hi matches character c for lo <= c <= hi
//
// Match requires pattern to match all of name, not just a substring.
// The only possible returned error is ErrBadPattern, when pattern
// is malformed.
//
// On Windows, escaping is disabled. Instead, '\\' is treated as
// path separator.
//