django.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. package view
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. stdPath "path"
  9. "path/filepath"
  10. "strings"
  11. "sync"
  12. "github.com/kataras/iris/context"
  13. "github.com/iris-contrib/pongo2"
  14. )
  15. type (
  16. // Value type alias for pongo2.Value
  17. Value = pongo2.Value
  18. // Error type alias for pongo2.Error
  19. Error = pongo2.Error
  20. // FilterFunction type alias for pongo2.FilterFunction
  21. FilterFunction = pongo2.FilterFunction
  22. // Parser type alias for pongo2.Parser
  23. Parser = pongo2.Parser
  24. // Token type alias for pongo2.Token
  25. Token = pongo2.Token
  26. // INodeTag type alias for pongo2.InodeTag
  27. INodeTag = pongo2.INodeTag
  28. // TagParser the function signature of the tag's parser you will have
  29. // to implement in order to create a new tag.
  30. //
  31. // 'doc' is providing access to the whole document while 'arguments'
  32. // is providing access to the user's arguments to the tag:
  33. //
  34. // {% your_tag_name some "arguments" 123 %}
  35. //
  36. // start_token will be the *Token with the tag's name in it (here: your_tag_name).
  37. //
  38. // Please see the Parser documentation on how to use the parser.
  39. // See `RegisterTag` for more information about writing a tag as well.
  40. TagParser = pongo2.TagParser
  41. )
  42. // AsValue converts any given value to a pongo2.Value
  43. // Usually being used within own functions passed to a template
  44. // through a Context or within filter functions.
  45. //
  46. // Example:
  47. // AsValue("my string")
  48. //
  49. // Shortcut for `pongo2.AsValue`.
  50. var AsValue = pongo2.AsValue
  51. // AsSafeValue works like AsValue, but does not apply the 'escape' filter.
  52. // Shortcut for `pongo2.AsSafeValue`.
  53. var AsSafeValue = pongo2.AsSafeValue
  54. type tDjangoAssetLoader struct {
  55. baseDir string
  56. assetGet func(name string) ([]byte, error)
  57. }
  58. // Abs calculates the path to a given template. Whenever a path must be resolved
  59. // due to an import from another template, the base equals the parent template's path.
  60. func (dal *tDjangoAssetLoader) Abs(base, name string) string {
  61. if stdPath.IsAbs(name) {
  62. return name
  63. }
  64. return stdPath.Join(dal.baseDir, name)
  65. }
  66. // Get returns an io.Reader where the template's content can be read from.
  67. func (dal *tDjangoAssetLoader) Get(path string) (io.Reader, error) {
  68. if stdPath.IsAbs(path) {
  69. path = path[1:]
  70. }
  71. res, err := dal.assetGet(path)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return bytes.NewBuffer(res), nil
  76. }
  77. // DjangoEngine contains the django view engine structure.
  78. type DjangoEngine struct {
  79. // files configuration
  80. directory string
  81. extension string
  82. assetFn func(name string) ([]byte, error) // for embedded, in combination with directory & extension
  83. namesFn func() []string // for embedded, in combination with directory & extension
  84. reload bool
  85. //
  86. rmu sync.RWMutex // locks for filters, globals and `ExecuteWiter` when `reload` is true.
  87. // filters for pongo2, map[name of the filter] the filter function . The filters are auto register
  88. filters map[string]FilterFunction
  89. // globals share context fields between templates.
  90. globals map[string]interface{}
  91. mu sync.Mutex // locks for template cache
  92. templateCache map[string]*pongo2.Template
  93. }
  94. var (
  95. _ Engine = (*DjangoEngine)(nil)
  96. _ EngineFuncer = (*DjangoEngine)(nil)
  97. )
  98. // Django creates and returns a new django view engine.
  99. // The given "extension" MUST begin with a dot.
  100. func Django(directory, extension string) *DjangoEngine {
  101. s := &DjangoEngine{
  102. directory: directory,
  103. extension: extension,
  104. globals: make(map[string]interface{}),
  105. filters: make(map[string]FilterFunction),
  106. templateCache: make(map[string]*pongo2.Template),
  107. }
  108. return s
  109. }
  110. // Ext returns the file extension which this view engine is responsible to render.
  111. func (s *DjangoEngine) Ext() string {
  112. return s.extension
  113. }
  114. // Binary optionally, use it when template files are distributed
  115. // inside the app executable (.go generated files).
  116. //
  117. // The assetFn and namesFn can come from the go-bindata library.
  118. func (s *DjangoEngine) Binary(assetFn func(name string) ([]byte, error), namesFn func() []string) *DjangoEngine {
  119. s.assetFn, s.namesFn = assetFn, namesFn
  120. return s
  121. }
  122. // Reload if set to true the templates are reloading on each render,
  123. // use it when you're in development and you're boring of restarting
  124. // the whole app when you edit a template file.
  125. //
  126. // Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time,
  127. // no concurrent access across clients, use it only on development status.
  128. // It's good to be used side by side with the https://github.com/kataras/rizla reloader for go source files.
  129. func (s *DjangoEngine) Reload(developmentMode bool) *DjangoEngine {
  130. s.reload = developmentMode
  131. return s
  132. }
  133. // AddFunc adds the function to the template's Globals.
  134. // It is legal to overwrite elements of the default actions:
  135. // - url func(routeName string, args ...string) string
  136. // - urlpath func(routeName string, args ...string) string
  137. // - render func(fullPartialName string) (template.HTML, error).
  138. func (s *DjangoEngine) AddFunc(funcName string, funcBody interface{}) {
  139. s.rmu.Lock()
  140. s.globals[funcName] = funcBody
  141. s.rmu.Unlock()
  142. }
  143. // AddFilter registers a new filter. If there's already a filter with the same
  144. // name, RegisterFilter will panic. You usually want to call this
  145. // function in the filter's init() function:
  146. // http://golang.org/doc/effective_go.html#init
  147. //
  148. // Same as `RegisterFilter`.
  149. func (s *DjangoEngine) AddFilter(filterName string, filterBody FilterFunction) *DjangoEngine {
  150. return s.registerFilter(filterName, filterBody)
  151. }
  152. // RegisterFilter registers a new filter. If there's already a filter with the same
  153. // name, RegisterFilter will panic. You usually want to call this
  154. // function in the filter's init() function:
  155. // http://golang.org/doc/effective_go.html#init
  156. //
  157. // See http://www.florian-schlachter.de/post/pongo2/ for more about
  158. // writing filters and tags.
  159. func (s *DjangoEngine) RegisterFilter(filterName string, filterBody FilterFunction) *DjangoEngine {
  160. return s.registerFilter(filterName, filterBody)
  161. }
  162. func (s *DjangoEngine) registerFilter(filterName string, fn FilterFunction) *DjangoEngine {
  163. pongo2.RegisterFilter(filterName, fn)
  164. return s
  165. }
  166. // RegisterTag registers a new tag. You usually want to call this
  167. // function in the tag's init() function:
  168. // http://golang.org/doc/effective_go.html#init
  169. //
  170. // See http://www.florian-schlachter.de/post/pongo2/ for more about
  171. // writing filters and tags.
  172. func (s *DjangoEngine) RegisterTag(tagName string, fn TagParser) error {
  173. return pongo2.RegisterTag(tagName, fn)
  174. }
  175. // Load parses the templates to the engine.
  176. // It is responsible to add the necessary global functions.
  177. //
  178. // Returns an error if something bad happens, user is responsible to catch it.
  179. func (s *DjangoEngine) Load() error {
  180. if s.assetFn != nil && s.namesFn != nil {
  181. // embedded
  182. return s.loadAssets()
  183. }
  184. // load from directory, make the dir absolute here too.
  185. dir, err := filepath.Abs(s.directory)
  186. if err != nil {
  187. return err
  188. }
  189. if _, err := os.Stat(dir); os.IsNotExist(err) {
  190. return err
  191. }
  192. // change the directory field configuration, load happens after directory has been set, so we will not have any problems here.
  193. s.directory = dir
  194. return s.loadDirectory()
  195. }
  196. // LoadDirectory loads the templates from directory.
  197. func (s *DjangoEngine) loadDirectory() (templateErr error) {
  198. dir, extension := s.directory, s.extension
  199. fsLoader, err := pongo2.NewLocalFileSystemLoader(dir) // I see that this doesn't read the content if already parsed, so do it manually via filepath.Walk
  200. if err != nil {
  201. return err
  202. }
  203. set := pongo2.NewSet("", fsLoader)
  204. set.Globals = getPongoContext(s.globals)
  205. s.mu.Lock()
  206. defer s.mu.Unlock()
  207. // Walk the supplied directory and compile any files that match our extension list.
  208. err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  209. // Fix same-extension-dirs bug: some dir might be named to: "users.tmpl", "local.html".
  210. // These dirs should be excluded as they are not valid golang templates, but files under
  211. // them should be treat as normal.
  212. // If is a dir, return immediately (dir is not a valid golang template).
  213. if info == nil || info.IsDir() {
  214. } else {
  215. rel, err := filepath.Rel(dir, path)
  216. if err != nil {
  217. templateErr = err
  218. return err
  219. }
  220. ext := filepath.Ext(rel)
  221. if ext == extension {
  222. buf, err := ioutil.ReadFile(path)
  223. if err != nil {
  224. templateErr = err
  225. return err
  226. }
  227. name := filepath.ToSlash(rel)
  228. s.templateCache[name], templateErr = set.FromString(string(buf))
  229. if templateErr != nil {
  230. return templateErr
  231. }
  232. }
  233. }
  234. return nil
  235. })
  236. if err != nil {
  237. return err
  238. }
  239. return
  240. }
  241. // loadAssets loads the templates by binary (go-bindata for embedded).
  242. func (s *DjangoEngine) loadAssets() error {
  243. virtualDirectory, virtualExtension := s.directory, s.extension
  244. assetFn, namesFn := s.assetFn, s.namesFn
  245. // Make a file set with a template loader based on asset function
  246. set := pongo2.NewSet("", &tDjangoAssetLoader{baseDir: s.directory, assetGet: s.assetFn})
  247. set.Globals = getPongoContext(s.globals)
  248. if len(virtualDirectory) > 0 {
  249. if virtualDirectory[0] == '.' { // first check for .wrong
  250. virtualDirectory = virtualDirectory[1:]
  251. }
  252. if virtualDirectory[0] == '/' || virtualDirectory[0] == os.PathSeparator { // second check for /something, (or ./something if we had dot on 0 it will be removed
  253. virtualDirectory = virtualDirectory[1:]
  254. }
  255. }
  256. s.mu.Lock()
  257. defer s.mu.Unlock()
  258. names := namesFn()
  259. for _, path := range names {
  260. if !strings.HasPrefix(path, virtualDirectory) {
  261. continue
  262. }
  263. rel, err := filepath.Rel(virtualDirectory, path)
  264. if err != nil {
  265. return err
  266. }
  267. ext := filepath.Ext(rel)
  268. if ext == virtualExtension {
  269. buf, err := assetFn(path)
  270. if err != nil {
  271. return err
  272. }
  273. name := filepath.ToSlash(rel)
  274. s.templateCache[name], err = set.FromString(string(buf))
  275. if err != nil {
  276. return err
  277. }
  278. }
  279. }
  280. return nil
  281. }
  282. // getPongoContext returns the pongo2.Context from map[string]interface{} or from pongo2.Context, used internaly
  283. func getPongoContext(templateData interface{}) pongo2.Context {
  284. if templateData == nil {
  285. return nil
  286. }
  287. if contextData, isPongoContext := templateData.(pongo2.Context); isPongoContext {
  288. return contextData
  289. }
  290. if contextData, isContextViewData := templateData.(context.Map); isContextViewData {
  291. return pongo2.Context(contextData)
  292. }
  293. return templateData.(map[string]interface{})
  294. }
  295. func (s *DjangoEngine) fromCache(relativeName string) *pongo2.Template {
  296. s.mu.Lock()
  297. tmpl, ok := s.templateCache[relativeName]
  298. if ok {
  299. s.mu.Unlock()
  300. return tmpl
  301. }
  302. s.mu.Unlock()
  303. return nil
  304. }
  305. // ExecuteWriter executes a templates and write its results to the w writer
  306. // layout here is useless.
  307. func (s *DjangoEngine) ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error {
  308. // re-parse the templates if reload is enabled.
  309. if s.reload {
  310. // locks to fix #872, it's the simplest solution and the most correct,
  311. // to execute writers with "wait list", one at a time.
  312. s.rmu.Lock()
  313. defer s.rmu.Unlock()
  314. if err := s.Load(); err != nil {
  315. return err
  316. }
  317. }
  318. if tmpl := s.fromCache(filename); tmpl != nil {
  319. return tmpl.ExecuteWriter(getPongoContext(bindingData), w)
  320. }
  321. return fmt.Errorf("template with name: %s ddoes not exist in the dir: %s", filename, s.directory)
  322. }