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.
 
 
 
 
 

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