engine.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package template // import "miniflux.app/template"
  5. import (
  6. "bytes"
  7. "html/template"
  8. "time"
  9. "miniflux.app/errors"
  10. "miniflux.app/locale"
  11. "miniflux.app/logger"
  12. "github.com/gorilla/mux"
  13. )
  14. // Engine handles the templating system.
  15. type Engine struct {
  16. templates map[string]*template.Template
  17. funcMap *funcMap
  18. }
  19. func (e *Engine) parseAll() {
  20. commonTemplates := ""
  21. for _, content := range templateCommonMap {
  22. commonTemplates += content
  23. }
  24. for name, content := range templateViewsMap {
  25. logger.Debug("[Template] Parsing: %s", name)
  26. e.templates[name] = template.Must(template.New("main").Funcs(e.funcMap.Map()).Parse(commonTemplates + content))
  27. }
  28. }
  29. // Render process a template.
  30. func (e *Engine) Render(name, language string, data interface{}) []byte {
  31. tpl, ok := e.templates[name]
  32. if !ok {
  33. logger.Fatal("[Template] The template %s does not exists", name)
  34. }
  35. printer := locale.NewPrinter(language)
  36. // Functions that need to be declared at runtime.
  37. tpl.Funcs(template.FuncMap{
  38. "elapsed": func(timezone string, t time.Time) string {
  39. return elapsedTime(printer, timezone, t)
  40. },
  41. "t": func(key interface{}, args ...interface{}) string {
  42. switch k := key.(type) {
  43. case string:
  44. return printer.Printf(k, args...)
  45. case errors.LocalizedError:
  46. return k.Localize(printer)
  47. case *errors.LocalizedError:
  48. return k.Localize(printer)
  49. case error:
  50. return k.Error()
  51. default:
  52. return ""
  53. }
  54. },
  55. "plural": func(key string, n int, args ...interface{}) string {
  56. return printer.Plural(key, n, args...)
  57. },
  58. "timeToRead": func(content string) int {
  59. return timeToRead(content)
  60. },
  61. })
  62. var b bytes.Buffer
  63. err := tpl.ExecuteTemplate(&b, "base", data)
  64. if err != nil {
  65. logger.Fatal("[Template] Unable to render template: %v", err)
  66. }
  67. return b.Bytes()
  68. }
  69. // NewEngine returns a new template engine.
  70. func NewEngine(router *mux.Router) *Engine {
  71. tpl := &Engine{
  72. templates: make(map[string]*template.Template),
  73. funcMap: &funcMap{router},
  74. }
  75. tpl.parseAll()
  76. return tpl
  77. }