mirror of
https://github.com/kataras/iris.git
synced 2025-12-29 07:47:22 +00:00
Full support of the http.FileSystem on all view engines as requested at #1575
Also, the HandleDir accepts both string and http.FileSystem (interface{}) (like the view's fs)
This commit is contained in:
280
view/html.go
280
view/html.go
@@ -5,7 +5,7 @@ import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -14,14 +14,16 @@ import (
|
||||
|
||||
// HTMLEngine contains the html view engine structure.
|
||||
type HTMLEngine struct {
|
||||
// the file system to load from.
|
||||
fs http.FileSystem
|
||||
// files configuration
|
||||
directory string
|
||||
rootDir string
|
||||
extension string
|
||||
assetFn func(name string) ([]byte, error) // for embedded, in combination with directory & extension
|
||||
namesFn func() []string // for embedded, in combination with directory & extension
|
||||
reload bool // if true, each time the ExecuteWriter is called the templates will be reloaded, each ExecuteWriter waits to be finished before writing to a new one.
|
||||
// if true, each time the ExecuteWriter is called the templates will be reloaded,
|
||||
// each ExecuteWriter waits to be finished before writing to a new one.
|
||||
reload bool
|
||||
// parser configuration
|
||||
options []string // text options
|
||||
options []string // (text) template options
|
||||
left string
|
||||
right string
|
||||
layout string
|
||||
@@ -65,12 +67,16 @@ var emptyFuncs = template.FuncMap{
|
||||
// The html engine used like the "html/template" standard go package
|
||||
// but with a lot of extra features.
|
||||
// The given "extension" MUST begin with a dot.
|
||||
func HTML(directory, extension string) *HTMLEngine {
|
||||
//
|
||||
// Usage:
|
||||
// HTML("./views", ".html") or
|
||||
// HTML(iris.Dir("./views"), ".html") or
|
||||
// HTML(AssetFile(), ".html") for embedded data.
|
||||
func HTML(fs interface{}, extension string) *HTMLEngine {
|
||||
s := &HTMLEngine{
|
||||
directory: directory,
|
||||
fs: getFS(fs),
|
||||
rootDir: "/",
|
||||
extension: extension,
|
||||
assetFn: nil,
|
||||
namesFn: nil,
|
||||
reload: false,
|
||||
left: "{{",
|
||||
right: "}}",
|
||||
@@ -82,20 +88,18 @@ func HTML(directory, extension string) *HTMLEngine {
|
||||
return s
|
||||
}
|
||||
|
||||
// RootDir sets the directory to be used as a starting point
|
||||
// to load templates from the provided file system.
|
||||
func (s *HTMLEngine) RootDir(root string) *HTMLEngine {
|
||||
s.rootDir = filepath.ToSlash(root)
|
||||
return s
|
||||
}
|
||||
|
||||
// Ext returns the file extension which this view engine is responsible to render.
|
||||
func (s *HTMLEngine) Ext() string {
|
||||
return s.extension
|
||||
}
|
||||
|
||||
// Binary optionally, use it when template files are distributed
|
||||
// inside the app executable (.go generated files).
|
||||
//
|
||||
// The assetFn and namesFn can come from the go-bindata library.
|
||||
func (s *HTMLEngine) Binary(assetFn func(name string) ([]byte, error), namesFn func() []string) *HTMLEngine {
|
||||
s.assetFn, s.namesFn = assetFn, namesFn
|
||||
return s
|
||||
}
|
||||
|
||||
// Reload if set to true the templates are reloading on each render,
|
||||
// use it when you're in development and you're boring of restarting
|
||||
// the whole app when you edit a template file.
|
||||
@@ -211,213 +215,49 @@ func (s *HTMLEngine) Funcs(funcMap template.FuncMap) *HTMLEngine {
|
||||
//
|
||||
// Returns an error if something bad happens, caller is responsible to handle that.
|
||||
func (s *HTMLEngine) Load() error {
|
||||
// No need to make this with a complicated and "pro" way, just add lockers to the `ExecuteWriter`.
|
||||
// if `Reload(true)` and add a note for non conc access on dev mode.
|
||||
// atomic.StoreUint32(&s.isLoading, 1)
|
||||
// s.rmu.Lock()
|
||||
// defer func() {
|
||||
// s.rmu.Unlock()
|
||||
// atomic.StoreUint32(&s.isLoading, 0)
|
||||
// }()
|
||||
s.rmu.Lock()
|
||||
defer s.rmu.Unlock()
|
||||
|
||||
if s.assetFn != nil && s.namesFn != nil {
|
||||
// NOT NECESSARY "fix" of https://github.com/kataras/iris/issues/784,
|
||||
// IT'S BAD CODE WRITTEN WE KEEP HERE ONLY FOR A REMINDER
|
||||
// for any future questions.
|
||||
//
|
||||
// if strings.HasPrefix(s.directory, "../") {
|
||||
// // this and some more additions are fixes for https://github.com/kataras/iris/issues/784
|
||||
// // however, the dev SHOULD
|
||||
// // run the go-bindata command from the "$dir" parent directory
|
||||
// // and just use the ./$dir in the declaration,
|
||||
// // so all these fixes are not really necessary but they are here
|
||||
// // for the future
|
||||
// dir, err := filepath.Abs(s.directory)
|
||||
// // the absolute dir here can be invalid if running from other
|
||||
// // folder but we really don't care
|
||||
// // when we're working with the bindata because
|
||||
// // we only care for its relative directory
|
||||
// // see `loadAssets` for more.
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// s.directory = dir
|
||||
// }
|
||||
|
||||
// embedded
|
||||
return s.loadAssets()
|
||||
}
|
||||
|
||||
// load from directory, make the dir absolute here too.
|
||||
dir, err := filepath.Abs(s.directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
// change the directory field configuration, load happens after directory has been set, so we will not have any problems here.
|
||||
s.directory = dir
|
||||
return s.loadDirectory()
|
||||
}
|
||||
|
||||
// loadDirectory builds the templates from directory.
|
||||
func (s *HTMLEngine) loadDirectory() error {
|
||||
dir, extension := s.directory, s.extension
|
||||
|
||||
var templateErr error
|
||||
s.Templates = template.New(dir)
|
||||
s.Templates = template.New(s.rootDir)
|
||||
s.Templates.Delims(s.left, s.right)
|
||||
|
||||
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
|
||||
return walk(s.fs, s.rootDir, func(path string, info os.FileInfo, err error) error {
|
||||
if info == nil || info.IsDir() {
|
||||
} else {
|
||||
rel, err := filepath.Rel(dir, path)
|
||||
return nil
|
||||
}
|
||||
|
||||
if s.extension != "" {
|
||||
if !strings.HasSuffix(path, s.extension) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
buf, err := asset(s.fs, path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", path, err)
|
||||
}
|
||||
contents := string(buf)
|
||||
|
||||
name := strings.TrimPrefix(path, "/")
|
||||
tmpl := s.Templates.New(name)
|
||||
tmpl.Option(s.options...)
|
||||
|
||||
if s.middleware != nil {
|
||||
contents, err = s.middleware(name, buf)
|
||||
if err != nil {
|
||||
templateErr = err
|
||||
return err
|
||||
}
|
||||
|
||||
ext := filepath.Ext(path)
|
||||
if ext == extension {
|
||||
|
||||
buf, err := ioutil.ReadFile(path)
|
||||
if err != nil {
|
||||
templateErr = err
|
||||
return err
|
||||
}
|
||||
|
||||
contents := string(buf)
|
||||
|
||||
name := filepath.ToSlash(rel)
|
||||
tmpl := s.Templates.New(name)
|
||||
tmpl.Option(s.options...)
|
||||
|
||||
if s.middleware != nil {
|
||||
contents, err = s.middleware(name, buf)
|
||||
}
|
||||
if err != nil {
|
||||
templateErr = err
|
||||
return err
|
||||
}
|
||||
// s.mu.Lock()
|
||||
// Add our funcmaps.
|
||||
_, err = tmpl.
|
||||
Funcs(emptyFuncs).
|
||||
// Funcs(s.makeDefaultLayoutFuncs(name)).
|
||||
// Funcs(s.layoutFuncs).
|
||||
Funcs(s.funcs).
|
||||
Parse(contents)
|
||||
// s.mu.Unlock()
|
||||
if err != nil {
|
||||
templateErr = err
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
// Add our funcmaps.
|
||||
_, err = tmpl.
|
||||
Funcs(emptyFuncs).
|
||||
// Funcs(s.makeDefaultLayoutFuncs(name)).
|
||||
// Funcs(s.layoutFuncs).
|
||||
Funcs(s.funcs).
|
||||
Parse(contents)
|
||||
return err
|
||||
}
|
||||
|
||||
return templateErr
|
||||
}
|
||||
|
||||
// loadAssets loads the templates by binary (go-bindata for embedded).
|
||||
func (s *HTMLEngine) loadAssets() error {
|
||||
virtualDirectory, virtualExtension := s.directory, s.extension
|
||||
assetFn, namesFn := s.assetFn, s.namesFn
|
||||
|
||||
var templateErr error
|
||||
s.Templates = template.New(virtualDirectory)
|
||||
s.Templates.Delims(s.left, s.right)
|
||||
names := namesFn()
|
||||
if len(virtualDirectory) > 0 {
|
||||
if virtualDirectory[0] == '.' { // first check for .wrong
|
||||
virtualDirectory = virtualDirectory[1:]
|
||||
}
|
||||
if virtualDirectory[0] == '/' || virtualDirectory[0] == os.PathSeparator { // second check for /something, (or ./something if we had dot on 0 it will be removed
|
||||
virtualDirectory = virtualDirectory[1:]
|
||||
}
|
||||
}
|
||||
|
||||
for _, path := range names {
|
||||
// if filepath.IsAbs(virtualDirectory) {
|
||||
// // fixes https://github.com/kataras/iris/issues/784
|
||||
// // we take the absolute fullpath of the template file.
|
||||
// pathFileAbs, err := filepath.Abs(path)
|
||||
// if err != nil {
|
||||
// templateErr = err
|
||||
// continue
|
||||
// }
|
||||
//
|
||||
// path = pathFileAbs
|
||||
// }
|
||||
|
||||
// bindata may contain more files than the templates
|
||||
// so keep that check as it's.
|
||||
if !strings.HasPrefix(path, virtualDirectory) {
|
||||
continue
|
||||
}
|
||||
|
||||
ext := filepath.Ext(path)
|
||||
// check if extension matches
|
||||
if ext == virtualExtension {
|
||||
|
||||
// take the relative path of the path as base of
|
||||
// virtualDirectory (the absolute path of the view engine that dev passed).
|
||||
rel, err := filepath.Rel(virtualDirectory, path)
|
||||
if err != nil {
|
||||
templateErr = err
|
||||
break
|
||||
}
|
||||
|
||||
// // take the current working directory
|
||||
// cpath, err := filepath.Abs(".")
|
||||
// if err == nil {
|
||||
// // set the path as relative to "path" of the current working dir.
|
||||
// // fixes https://github.com/kataras/iris/issues/784
|
||||
// rpath, err := filepath.Rel(cpath, path)
|
||||
// // fix view: Asset not found for path ''
|
||||
// if err == nil && rpath != "" {
|
||||
// path = rpath
|
||||
// }
|
||||
// }
|
||||
|
||||
buf, err := assetFn(path)
|
||||
if err != nil {
|
||||
templateErr = fmt.Errorf("%v for path '%s'", err, path)
|
||||
break
|
||||
}
|
||||
|
||||
contents := string(buf)
|
||||
name := filepath.ToSlash(rel)
|
||||
|
||||
// name should be the filename of the template.
|
||||
tmpl := s.Templates.New(name)
|
||||
tmpl.Option(s.options...)
|
||||
|
||||
if s.middleware != nil {
|
||||
contents, err = s.middleware(name, buf)
|
||||
if err != nil {
|
||||
templateErr = fmt.Errorf("%v for name '%s'", err, name)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Add our funcmaps.
|
||||
if _, err = tmpl.Funcs(emptyFuncs).Funcs(s.funcs).Parse(contents); err != nil {
|
||||
templateErr = err
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return templateErr
|
||||
})
|
||||
}
|
||||
|
||||
func (s *HTMLEngine) executeTemplateBuf(name string, binding interface{}) (*bytes.Buffer, error) {
|
||||
@@ -494,10 +334,6 @@ func (s *HTMLEngine) runtimeFuncsFor(t *template.Template, name string, binding
|
||||
func (s *HTMLEngine) ExecuteWriter(w io.Writer, name string, layout string, bindingData interface{}) error {
|
||||
// re-parse the templates if reload is enabled.
|
||||
if s.reload {
|
||||
// locks to fix #872, it's the simplest solution and the most correct,
|
||||
// to execute writers with "wait list", one at a time.
|
||||
s.rmu.Lock()
|
||||
defer s.rmu.Unlock()
|
||||
if err := s.Load(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -505,14 +341,14 @@ func (s *HTMLEngine) ExecuteWriter(w io.Writer, name string, layout string, bind
|
||||
|
||||
t := s.Templates.Lookup(name)
|
||||
if t == nil {
|
||||
return fmt.Errorf("template: %s does not exist in the dir: %s", name, s.directory)
|
||||
return ErrNotExist{name, false}
|
||||
}
|
||||
s.runtimeFuncsFor(t, name, bindingData)
|
||||
|
||||
if layout = getLayout(layout, s.layout); layout != "" {
|
||||
lt := s.Templates.Lookup(layout)
|
||||
if lt == nil {
|
||||
return fmt.Errorf("layout: %s does not exist in the dir: %s", name, s.directory)
|
||||
return ErrNotExist{name, true}
|
||||
}
|
||||
|
||||
s.layoutFuncsFor(lt, name, bindingData)
|
||||
|
||||
Reference in New Issue
Block a user