A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

198 lines
5.4 KiB

  1. /*
  2. * Copyright © 2018 A Bunch Tell LLC.
  3. *
  4. * This file is part of WriteFreely.
  5. *
  6. * WriteFreely is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License, included
  8. * in the LICENSE file in this source code package.
  9. */
  10. package writefreely
  11. import (
  12. "github.com/dustin/go-humanize"
  13. "github.com/writeas/web-core/l10n"
  14. "github.com/writeas/web-core/log"
  15. "github.com/writeas/writefreely/config"
  16. "html/template"
  17. "io"
  18. "io/ioutil"
  19. "net/http"
  20. "os"
  21. "path/filepath"
  22. "strings"
  23. )
  24. var (
  25. templates = map[string]*template.Template{}
  26. pages = map[string]*template.Template{}
  27. userPages = map[string]*template.Template{}
  28. funcMap = template.FuncMap{
  29. "largeNumFmt": largeNumFmt,
  30. "pluralize": pluralize,
  31. "isRTL": isRTL,
  32. "isLTR": isLTR,
  33. "localstr": localStr,
  34. "localhtml": localHTML,
  35. "tolower": strings.ToLower,
  36. }
  37. )
  38. const (
  39. templatesDir = "templates"
  40. pagesDir = "pages"
  41. )
  42. func showUserPage(w http.ResponseWriter, name string, obj interface{}) {
  43. if obj == nil {
  44. log.Error("showUserPage: data is nil!")
  45. return
  46. }
  47. if err := userPages[filepath.Join("user", name+".tmpl")].ExecuteTemplate(w, name, obj); err != nil {
  48. log.Error("Error parsing %s: %v", name, err)
  49. }
  50. }
  51. func initTemplate(parentDir, name string) {
  52. if debugging {
  53. log.Info(" " + filepath.Join(parentDir, templatesDir, name+".tmpl"))
  54. }
  55. files := []string{
  56. filepath.Join(parentDir, templatesDir, name+".tmpl"),
  57. filepath.Join(parentDir, templatesDir, "include", "footer.tmpl"),
  58. filepath.Join(parentDir, templatesDir, "base.tmpl"),
  59. }
  60. if name == "collection" || name == "collection-tags" || name == "chorus-collection" {
  61. // These pages list out collection posts, so we also parse templatesDir + "include/posts.tmpl"
  62. files = append(files, filepath.Join(parentDir, templatesDir, "include", "posts.tmpl"))
  63. }
  64. if name == "chorus-collection" || name == "chorus-collection-post" {
  65. files = append(files, filepath.Join(parentDir, templatesDir, "user", "include", "header.tmpl"))
  66. }
  67. if name == "collection" || name == "collection-tags" || name == "collection-post" || name == "post" || name == "chorus-collection" || name == "chorus-collection-post" {
  68. files = append(files, filepath.Join(parentDir, templatesDir, "include", "post-render.tmpl"))
  69. }
  70. templates[name] = template.Must(template.New("").Funcs(funcMap).ParseFiles(files...))
  71. }
  72. func initPage(parentDir, path, key string) {
  73. if debugging {
  74. log.Info(" [%s] %s", key, path)
  75. }
  76. pages[key] = template.Must(template.New("").Funcs(funcMap).ParseFiles(
  77. path,
  78. filepath.Join(parentDir, templatesDir, "include", "footer.tmpl"),
  79. filepath.Join(parentDir, templatesDir, "base.tmpl"),
  80. ))
  81. }
  82. func initUserPage(parentDir, path, key string) {
  83. if debugging {
  84. log.Info(" [%s] %s", key, path)
  85. }
  86. userPages[key] = template.Must(template.New(key).Funcs(funcMap).ParseFiles(
  87. path,
  88. filepath.Join(parentDir, templatesDir, "user", "include", "header.tmpl"),
  89. filepath.Join(parentDir, templatesDir, "user", "include", "footer.tmpl"),
  90. ))
  91. }
  92. // InitTemplates loads all template files from the configured parent dir.
  93. func InitTemplates(cfg *config.Config) error {
  94. log.Info("Loading templates...")
  95. tmplFiles, err := ioutil.ReadDir(filepath.Join(cfg.Server.TemplatesParentDir, templatesDir))
  96. if err != nil {
  97. return err
  98. }
  99. for _, f := range tmplFiles {
  100. if !f.IsDir() && !strings.HasPrefix(f.Name(), ".") {
  101. parts := strings.Split(f.Name(), ".")
  102. key := parts[0]
  103. initTemplate(cfg.Server.TemplatesParentDir, key)
  104. }
  105. }
  106. log.Info("Loading pages...")
  107. // Initialize all static pages that use the base template
  108. filepath.Walk(filepath.Join(cfg.Server.PagesParentDir, pagesDir), func(path string, i os.FileInfo, err error) error {
  109. if !i.IsDir() && !strings.HasPrefix(i.Name(), ".") {
  110. key := i.Name()
  111. initPage(cfg.Server.PagesParentDir, path, key)
  112. }
  113. return nil
  114. })
  115. log.Info("Loading user pages...")
  116. // Initialize all user pages that use base templates
  117. filepath.Walk(filepath.Join(cfg.Server.TemplatesParentDir, templatesDir, "user"), func(path string, f os.FileInfo, err error) error {
  118. if !f.IsDir() && !strings.HasPrefix(f.Name(), ".") {
  119. corePath := path
  120. if cfg.Server.TemplatesParentDir != "" {
  121. corePath = corePath[len(cfg.Server.TemplatesParentDir)+1:]
  122. }
  123. parts := strings.Split(corePath, string(filepath.Separator))
  124. key := f.Name()
  125. if len(parts) > 2 {
  126. key = filepath.Join(parts[1], f.Name())
  127. }
  128. initUserPage(cfg.Server.TemplatesParentDir, path, key)
  129. }
  130. return nil
  131. })
  132. return nil
  133. }
  134. // renderPage retrieves the given template and renders it to the given io.Writer.
  135. // If something goes wrong, the error is logged and returned.
  136. func renderPage(w io.Writer, tmpl string, data interface{}) error {
  137. err := pages[tmpl].ExecuteTemplate(w, "base", data)
  138. if err != nil {
  139. log.Error("%v", err)
  140. }
  141. return err
  142. }
  143. func largeNumFmt(n int64) string {
  144. return humanize.Comma(n)
  145. }
  146. func pluralize(singular, plural string, n int64) string {
  147. if n == 1 {
  148. return singular
  149. }
  150. return plural
  151. }
  152. func isRTL(d string) bool {
  153. return d == "rtl"
  154. }
  155. func isLTR(d string) bool {
  156. return d == "ltr" || d == "auto"
  157. }
  158. func localStr(term, lang string) string {
  159. s := l10n.Strings(lang)[term]
  160. if s == "" {
  161. s = l10n.Strings("")[term]
  162. }
  163. return s
  164. }
  165. func localHTML(term, lang string) template.HTML {
  166. s := l10n.Strings(lang)[term]
  167. if s == "" {
  168. s = l10n.Strings("")[term]
  169. }
  170. s = strings.Replace(s, "write.as", "<a href=\"https://writefreely.org\">writefreely</a>", 1)
  171. return template.HTML(s)
  172. }