django.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. package view
  2. import (
  3. "bytes"
  4. "io"
  5. "io/fs"
  6. "os"
  7. stdPath "path"
  8. "path/filepath"
  9. "strings"
  10. "sync"
  11. "github.com/kataras/iris/v12/context"
  12. "github.com/fatih/structs"
  13. "github.com/flosch/pongo2/v4"
  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. //
  48. // AsValue("my string")
  49. //
  50. // Shortcut for `pongo2.AsValue`.
  51. var AsValue = pongo2.AsValue
  52. // AsSafeValue works like AsValue, but does not apply the 'escape' filter.
  53. // Shortcut for `pongo2.AsSafeValue`.
  54. var AsSafeValue = pongo2.AsSafeValue
  55. type tDjangoAssetLoader struct {
  56. rootDir string
  57. fs fs.FS
  58. }
  59. // Abs calculates the path to a given template. Whenever a path must be resolved
  60. // due to an import from another template, the base equals the parent template's path.
  61. func (l *tDjangoAssetLoader) Abs(base, name string) string {
  62. if stdPath.IsAbs(name) {
  63. return name
  64. }
  65. return stdPath.Join(l.rootDir, name)
  66. }
  67. // Get returns an io.Reader where the template's content can be read from.
  68. func (l *tDjangoAssetLoader) Get(path string) (io.Reader, error) {
  69. if stdPath.IsAbs(path) {
  70. path = path[1:]
  71. }
  72. res, err := asset(l.fs, path)
  73. if err != nil {
  74. return nil, err
  75. }
  76. return bytes.NewReader(res), nil
  77. }
  78. // DjangoEngine contains the django view engine structure.
  79. type DjangoEngine struct {
  80. fs fs.FS
  81. // files configuration
  82. rootDir string
  83. extension string
  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. Set *pongo2.TemplateSet
  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. //
  101. // Usage:
  102. // Django("./views", ".html") or
  103. // Django(iris.Dir("./views"), ".html") or
  104. // Django(embed.FS, ".html") or Django(AssetFile(), ".html") for embedded data.
  105. func Django(fs interface{}, extension string) *DjangoEngine {
  106. s := &DjangoEngine{
  107. fs: getFS(fs),
  108. rootDir: "/",
  109. extension: extension,
  110. globals: make(map[string]interface{}),
  111. filters: make(map[string]FilterFunction),
  112. templateCache: make(map[string]*pongo2.Template),
  113. }
  114. return s
  115. }
  116. // RootDir sets the directory to be used as a starting point
  117. // to load templates from the provided file system.
  118. func (s *DjangoEngine) RootDir(root string) *DjangoEngine {
  119. if s.fs != nil && root != "" && root != "/" && root != "." && root != s.rootDir {
  120. sub, err := fs.Sub(s.fs, s.rootDir)
  121. if err != nil {
  122. panic(err)
  123. }
  124. s.fs = sub // here so the "middleware" can work.
  125. }
  126. s.rootDir = filepath.ToSlash(root)
  127. return s
  128. }
  129. // Name returns the django engine's name.
  130. func (s *DjangoEngine) Name() string {
  131. return "Django"
  132. }
  133. // Ext returns the file extension which this view engine is responsible to render.
  134. // If the filename extension on ExecuteWriter is empty then this is appended.
  135. func (s *DjangoEngine) Ext() string {
  136. return s.extension
  137. }
  138. // Reload if set to true the templates are reloading on each render,
  139. // use it when you're in development and you're boring of restarting
  140. // the whole app when you edit a template file.
  141. //
  142. // Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time,
  143. // no concurrent access across clients, use it only on development status.
  144. // It's good to be used side by side with the https://github.com/kataras/rizla reloader for go source files.
  145. func (s *DjangoEngine) Reload(developmentMode bool) *DjangoEngine {
  146. s.reload = developmentMode
  147. return s
  148. }
  149. // AddFunc adds the function to the template's Globals.
  150. // It is legal to overwrite elements of the default actions:
  151. // - url func(routeName string, args ...string) string
  152. // - urlpath func(routeName string, args ...string) string
  153. // - render func(fullPartialName string) (template.HTML, error).
  154. func (s *DjangoEngine) AddFunc(funcName string, funcBody interface{}) {
  155. s.rmu.Lock()
  156. s.globals[funcName] = funcBody
  157. s.rmu.Unlock()
  158. }
  159. // AddFilter registers a new filter. If there's already a filter with the same
  160. // name, RegisterFilter will panic. You usually want to call this
  161. // function in the filter's init() function:
  162. // http://golang.org/doc/effective_go.html#init
  163. //
  164. // Same as `RegisterFilter`.
  165. func (s *DjangoEngine) AddFilter(filterName string, filterBody FilterFunction) *DjangoEngine {
  166. return s.registerFilter(filterName, filterBody)
  167. }
  168. // RegisterFilter registers a new filter. If there's already a filter with the same
  169. // name, RegisterFilter will panic. You usually want to call this
  170. // function in the filter's init() function:
  171. // http://golang.org/doc/effective_go.html#init
  172. //
  173. // See http://www.florian-schlachter.de/post/pongo2/ for more about
  174. // writing filters and tags.
  175. func (s *DjangoEngine) RegisterFilter(filterName string, filterBody FilterFunction) *DjangoEngine {
  176. return s.registerFilter(filterName, filterBody)
  177. }
  178. func (s *DjangoEngine) registerFilter(filterName string, fn FilterFunction) *DjangoEngine {
  179. pongo2.RegisterFilter(filterName, fn)
  180. return s
  181. }
  182. // RegisterTag registers a new tag. You usually want to call this
  183. // function in the tag's init() function:
  184. // http://golang.org/doc/effective_go.html#init
  185. //
  186. // See http://www.florian-schlachter.de/post/pongo2/ for more about
  187. // writing filters and tags.
  188. func (s *DjangoEngine) RegisterTag(tagName string, fn TagParser) error {
  189. return pongo2.RegisterTag(tagName, fn)
  190. }
  191. // Load parses the templates to the engine.
  192. // It is responsible to add the necessary global functions.
  193. //
  194. // Returns an error if something bad happens, user is responsible to catch it.
  195. func (s *DjangoEngine) Load() error {
  196. // If only custom templates should be loaded.
  197. if (s.fs == nil || context.IsNoOpFS(s.fs)) && len(s.templateCache) > 0 {
  198. return nil
  199. }
  200. rootDirName := getRootDirName(s.fs)
  201. return walk(s.fs, "", func(path string, info os.FileInfo, err error) error {
  202. if err != nil {
  203. return err
  204. }
  205. if info == nil || info.IsDir() {
  206. return nil
  207. }
  208. if s.extension != "" {
  209. if !strings.HasSuffix(path, s.extension) {
  210. return nil
  211. }
  212. }
  213. if s.rootDir == rootDirName {
  214. path = strings.TrimPrefix(path, rootDirName)
  215. path = strings.TrimPrefix(path, "/")
  216. }
  217. contents, err := asset(s.fs, path)
  218. if err != nil {
  219. return err
  220. }
  221. return s.ParseTemplate(path, contents)
  222. })
  223. }
  224. // ParseTemplate adds a custom template from text.
  225. // This parser does not support funcs per template. Use the `AddFunc` instead.
  226. func (s *DjangoEngine) ParseTemplate(name string, contents []byte) error {
  227. s.rmu.Lock()
  228. defer s.rmu.Unlock()
  229. s.initSet()
  230. name = strings.TrimPrefix(name, "/")
  231. tmpl, err := s.Set.FromBytes(contents)
  232. if err == nil {
  233. s.templateCache[name] = tmpl
  234. }
  235. return err
  236. }
  237. func (s *DjangoEngine) initSet() { // protected by the caller.
  238. if s.Set == nil {
  239. s.Set = pongo2.NewSet("", &tDjangoAssetLoader{fs: s.fs, rootDir: s.rootDir})
  240. s.Set.Globals = getPongoContext(s.globals)
  241. }
  242. }
  243. // getPongoContext returns the pongo2.Context from map[string]interface{} or from pongo2.Context, used internaly
  244. func getPongoContext(templateData interface{}) pongo2.Context {
  245. if templateData == nil {
  246. return nil
  247. }
  248. switch data := templateData.(type) {
  249. case pongo2.Context:
  250. return data
  251. case context.Map:
  252. return pongo2.Context(data)
  253. default:
  254. // if struct, convert it to map[string]interface{}
  255. if structs.IsStruct(data) {
  256. return pongo2.Context(structs.Map(data))
  257. }
  258. panic("django: template data: should be a map or struct")
  259. }
  260. }
  261. func (s *DjangoEngine) fromCache(relativeName string) *pongo2.Template {
  262. if s.reload {
  263. s.rmu.RLock()
  264. defer s.rmu.RUnlock()
  265. }
  266. if tmpl, ok := s.templateCache[relativeName]; ok {
  267. return tmpl
  268. }
  269. return nil
  270. }
  271. // ExecuteWriter executes a templates and write its results to the w writer
  272. // layout here is useless.
  273. func (s *DjangoEngine) ExecuteWriter(w io.Writer, filename string, _ string, bindingData interface{}) error {
  274. // re-parse the templates if reload is enabled.
  275. if s.reload {
  276. if err := s.Load(); err != nil {
  277. return err
  278. }
  279. }
  280. if tmpl := s.fromCache(filename); tmpl != nil {
  281. return tmpl.ExecuteWriter(getPongoContext(bindingData), w)
  282. }
  283. return ErrNotExist{Name: filename, IsLayout: false, Data: bindingData}
  284. }