template.ParseGlob() pattern to parse all files in a directory recursively ?

2,756 views
Skip to first unread message

briche...@gmail.com

unread,
Jul 26, 2013, 7:46:47 AM7/26/13
to golan...@googlegroups.com
Hi,

I think the object is self-descriptive.. I want to parse all the files ending in .html in a directory; recursively.
Is it possible with ParseGlob ?

Christoph Hack

unread,
Jul 26, 2013, 9:29:52 AM7/26/13
to golan...@googlegroups.com, briche...@gmail.com
I don't know, but I would use filepath.Walk directly. For example:

err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
    if err != nil {
      return err; // you can also return nil here if you want to skip files and directories that can not be accessed
    }
    if info.IsDir() || !strings.HasSuffix(".html") {
      return nil // ignore directories and other files
    }
    err = parseFile(path)
    return err
})

briche...@gmail.com

unread,
Jul 26, 2013, 11:10:29 AM7/26/13
to golan...@googlegroups.com, briche...@gmail.com
Thx Christoph, I followed your suggestion and ended up with a simple :

        template := template.New("template")

filepath.Walk("src/main/templates", func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".html") {
template.ParseFiles(path)
}

return nil
})

Shaban Naasso

unread,
Jul 29, 2013, 5:47:55 AM7/29/13
to golan...@googlegroups.com, briche...@gmail.com
don't forget to return the error code from ParseFiles otherwise you will have a hard time finding errors in your templates :-)

astr...@gmail.com

unread,
Sep 17, 2014, 7:29:36 AM9/17/14
to golan...@googlegroups.com, briche...@gmail.com
Hi there,

Maybe this help someone,

       const tp = "src"

pattern := filepath.Join(tp, "*.html")
tmpl := template.Must(template.ParseGlob(pattern))

william...@gmail.com

unread,
Apr 20, 2015, 11:11:58 AM4/20/15
to golan...@googlegroups.com, briche...@gmail.com
This only parses the html files in the existing directory, not subdirectories.  This does not solve the question being asked.  He is looking for a recursive version of this.
Reply all
Reply to author
Forward
0 new messages