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.
 
 
 
 
 

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