diff --git a/README.md b/README.md index e09df0f..5ffa2a7 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,7 @@ Render comes with a variety of configuration options _(Note: these are not the d // ... r := render.New(render.Options{ Directory: "templates", // Specify what path to load the templates from. + FileSystem: &LocalFileSystem{}, // Specify filesystem from where files are loaded. Asset: func(name string) ([]byte, error) { // Load from an Asset function instead of file. return []byte("template content"), nil }, @@ -117,6 +118,7 @@ r := render.New() r := render.New(render.Options{ Directory: "templates", + FileSystem: &LocalFileSystem{}, Asset: nil, AssetNames: nil, Layout: "", diff --git a/fs.go b/fs.go new file mode 100644 index 0000000..3e60776 --- /dev/null +++ b/fs.go @@ -0,0 +1,21 @@ +package render + +import ( + "io/ioutil" + "path/filepath" +) + +type FileSystem interface { + Walk(root string, walkFn filepath.WalkFunc) error + ReadFile(filename string) ([]byte, error) +} + +type LocalFileSystem struct{} + +func (LocalFileSystem) Walk(root string, walkFn filepath.WalkFunc) error { + return filepath.Walk(root, walkFn) +} + +func (LocalFileSystem) ReadFile(filename string) ([]byte, error) { + return ioutil.ReadFile(filename) +} diff --git a/render.go b/render.go index 0d7273f..674484b 100644 --- a/render.go +++ b/render.go @@ -5,7 +5,6 @@ import ( "fmt" "html/template" "io" - "io/ioutil" "log" "net/http" "os" @@ -51,6 +50,8 @@ type Delims struct { type Options struct { // Directory to load templates. Default is "templates". Directory string + // FileSystem to access files + FileSystem FileSystem // Asset function to use in place of directory. Defaults to nil. Asset func(name string) ([]byte, error) // AssetNames function to use in place of directory. Defaults to nil. @@ -149,6 +150,9 @@ func (r *Render) prepareOptions() { if len(r.opt.Directory) == 0 { r.opt.Directory = "templates" } + if r.opt.FileSystem == nil { + r.opt.FileSystem = &LocalFileSystem{} + } if len(r.opt.Extensions) == 0 { r.opt.Extensions = []string{".tmpl"} } @@ -186,7 +190,7 @@ func (r *Render) compileTemplatesFromDir() { r.templates.Delims(r.opt.Delims.Left, r.opt.Delims.Right) // Walk the supplied directory and compile any files that match our extension list. - filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + r.opt.FileSystem.Walk(dir, func(path string, info os.FileInfo, err error) error { // Fix same-extension-dirs bug: some dir might be named to: "users.tmpl", "local.html". // These dirs should be excluded as they are not valid golang templates, but files under // them should be treat as normal. @@ -207,7 +211,7 @@ func (r *Render) compileTemplatesFromDir() { for _, extension := range r.opt.Extensions { if ext == extension { - buf, err := ioutil.ReadFile(path) + buf, err := r.opt.FileSystem.ReadFile(path) if err != nil { panic(err) }