5

Golang Template Parse Directory

 2 years ago
source link: http://siongui.github.io/2017/02/13/go-template-parse-all-files-in-directory/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Golang Template Parse Directory

February 13, 2017

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

[3]GitHub - siongui/gotemplateutil: utility for Go template


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK