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.
 
 
 
 
 

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