Golang Template Parse Directory


There are ParseFiles and ParseGlob in Go text/template and html/template package, but sometimes we want to parse all files in a directory tree, so I write a ParseDirectory function to do this.

The code consists of two part:

  1. Use filepath.Walk to walk the file tree in the directory, and return all file paths in the directory.
// Recursively get all file paths in directory, including sub-directories.
func GetAllFilePathsInDirectory(dirpath string) ([]string, error) {
      var paths []string
      err := filepath.Walk(dirpath, func(path string, info os.FileInfo, err error) error {
              if err != nil {
                      return err
              }
              if !info.IsDir() {
                      paths = append(paths, path)
              }
              return nil
      })
      if err != nil {
              return nil, err
      }

      return paths, nil
}
  1. Pass the file paths to ParseFiles function in template package, and the parsed template will be returned.
// Recursively parse all files in directory, including sub-directories.
func ParseDirectory(dirpath string) (*template.Template, error) {
      paths, err := GetAllFilePathsInDirectory(dirpath)
      if err != nil {
              return nil, err
      }
      return template.ParseFiles(paths...)
}

Combine the above code, now we have ParseDirectory function, which takes directory path as argument and returns the parsed template.


Tested on:

  • Ubuntu Linux 16.10
  • Go 1.7.5

References:

[1][Golang] Walk All Files in Directory
[2]
[3]GitHub - siongui/gotemplateutil: utility for Go template