django.go 12 KB

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