GoBlog/render.go

236 lines
6.7 KiB
Go
Raw Normal View History

2020-07-31 13:48:01 +00:00
package main
import (
"bytes"
2020-11-01 17:37:21 +00:00
"errors"
2020-07-31 13:48:01 +00:00
"html/template"
"net/http"
"os"
"path"
"path/filepath"
"strings"
2020-10-06 17:07:48 +00:00
"go.goblog.app/app/pkgs/contenttype"
2020-07-31 13:48:01 +00:00
)
const (
templatesDir = "templates"
templatesExt = ".gohtml"
templateBase = "base"
templatePost = "post"
templateError = "error"
templateIndex = "index"
templateTaxonomy = "taxonomy"
templateSearch = "search"
templateSummary = "summary"
templatePhotosSummary = "photosummary"
templateEditor = "editor"
templateEditorFiles = "editorfiles"
templateLogin = "login"
templateStaticHome = "statichome"
templateBlogStats = "blogstats"
templateBlogStatsTable = "blogstatstable"
templateComment = "comment"
templateCaptcha = "captcha"
templateCommentsAdmin = "commentsadmin"
templateNotificationsAdmin = "notificationsadmin"
2021-02-20 22:35:16 +00:00
templateWebmentionAdmin = "webmentionadmin"
2021-05-08 19:22:48 +00:00
templateBlogroll = "blogroll"
2021-07-06 19:06:39 +00:00
templateGeoMap = "geomap"
2021-07-22 11:41:52 +00:00
templateContact = "contact"
2021-11-23 14:23:01 +00:00
templateIndieAuth = "indieauth"
)
2020-07-31 13:48:01 +00:00
func (a *goBlog) initRendering() error {
a.templates = map[string]*template.Template{}
2021-03-11 08:16:19 +00:00
templateFunctions := template.FuncMap{
2021-08-04 21:26:38 +00:00
"md": a.safeRenderMarkdownAsHTML,
"mdtitle": a.renderMdTitle,
"html": wrapStringAsHTML,
2020-10-18 09:54:29 +00:00
// Post specific
"content": a.postHtml,
"summary": a.postSummary,
"shorturl": a.shortPostURL,
"showfull": a.showFull,
"photolinks": a.photoLinks,
"gettrack": a.getTrack,
// Code based rendering
"posttax": func(p *post, b *configBlog) template.HTML {
var hb htmlBuilder
a.renderPostTax(&hb, p, b)
return hb.html()
},
"postmeta": func(p *post, b *configBlog, typ string) template.HTML {
var hb htmlBuilder
a.renderPostMeta(&hb, p, b, typ)
return hb.html()
},
"oldcontentwarning": func(p *post, b *configBlog) template.HTML {
var hb htmlBuilder
a.renderOldContentWarning(&hb, p, b)
return hb.html()
},
"interactions": func(b *configBlog, c string) template.HTML {
var hb htmlBuilder
a.renderInteractions(&hb, b, c)
return hb.html()
},
"author": func() template.HTML {
var hb htmlBuilder
a.renderAuthor(&hb)
return hb.html()
},
"postheadmeta": func(p *post, c string) template.HTML {
var hb htmlBuilder
a.renderPostHeadMeta(&hb, p, c)
return hb.html()
},
"tor": func(b *configBlog, torUsed bool, torAddress string) template.HTML {
var hb htmlBuilder
a.renderTorNotice(&hb, b, torUsed, torAddress)
return hb.html()
},
// Others
2021-08-01 17:27:21 +00:00
"dateformat": dateFormat,
"isodate": isoDateFormat,
"unixtodate": unixToLocalDateString,
"now": localNowString,
"asset": a.assetFileName,
"string": a.ts.GetTemplateStringVariantFunc(),
"include": a.includeRenderedTemplate,
"urlize": urlize,
"absolute": a.getFullAddress,
"opensearch": openSearchUrl,
"mbytes": mBytesString,
"editortemplate": a.editorPostTemplate,
"editorpostdesc": a.editorPostDesc,
"ttsenabled": a.ttsEnabled,
2020-07-31 13:48:01 +00:00
}
2021-03-11 08:16:19 +00:00
baseTemplate, err := template.New("base").Funcs(templateFunctions).ParseFiles(path.Join(templatesDir, templateBase+templatesExt))
if err != nil {
return err
}
err = filepath.Walk(templatesDir, func(p string, info os.FileInfo, err error) error {
2021-02-08 17:51:07 +00:00
if err != nil {
return err
}
if info.Mode().IsRegular() && path.Ext(p) == templatesExt {
2021-02-08 17:51:07 +00:00
if name := strings.TrimSuffix(path.Base(p), templatesExt); name != templateBase {
if a.templates[name], err = template.Must(baseTemplate.Clone()).New(name).ParseFiles(p); err != nil {
return err
}
}
}
return nil
2021-03-11 08:16:19 +00:00
})
if err != nil {
return err
}
return nil
}
2020-10-12 16:47:23 +00:00
type renderData struct {
BlogString string
Canonical string
2021-05-09 12:42:53 +00:00
TorAddress string
Blog *configBlog
User *configUser
Data interface{}
CommentsEnabled bool
WebmentionReceivingEnabled bool
2021-05-09 12:42:53 +00:00
TorUsed bool
2021-07-23 10:59:24 +00:00
EasterEgg bool
2021-07-25 08:53:12 +00:00
// Not directly accessible
app *goBlog
req *http.Request
}
func (d *renderData) LoggedIn() bool {
return d.app.isLoggedIn(d.req)
2020-10-12 16:47:23 +00:00
}
func (a *goBlog) render(w http.ResponseWriter, r *http.Request, template string, data *renderData) {
2021-06-19 06:37:16 +00:00
a.renderWithStatusCode(w, r, http.StatusOK, template, data)
}
func (a *goBlog) renderWithStatusCode(w http.ResponseWriter, r *http.Request, statusCode int, template string, data *renderData) {
2020-10-12 16:47:23 +00:00
// Check render data
2021-06-23 17:20:50 +00:00
a.checkRenderData(r, data)
// Set content type
w.Header().Set(contentType, contenttype.HTMLUTF8)
2021-12-30 11:40:21 +00:00
// Render template and write minified HTML
var templateBuffer bytes.Buffer
if err := a.templates[template].ExecuteTemplate(&templateBuffer, template, data); err != nil {
2021-06-23 17:20:50 +00:00
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(statusCode)
2021-12-30 11:40:21 +00:00
if err := a.min.Minify(contenttype.HTML, w, &templateBuffer); err != nil {
2021-06-23 17:20:50 +00:00
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (a *goBlog) checkRenderData(r *http.Request, data *renderData) {
2021-07-25 08:53:12 +00:00
if data.app == nil {
data.app = a
}
if data.req == nil {
data.req = r
}
2021-06-23 17:20:50 +00:00
// User
if data.User == nil {
data.User = a.cfg.User
}
2021-06-23 17:20:50 +00:00
// Blog
if data.Blog == nil && data.BlogString == "" {
data.BlogString, data.Blog = a.getBlog(r)
} else if data.Blog == nil {
data.Blog = a.cfg.Blogs[data.BlogString]
} else if data.BlogString == "" {
for name, blog := range a.cfg.Blogs {
if blog == data.Blog {
data.BlogString = name
2021-01-17 11:53:07 +00:00
break
}
2020-10-12 16:47:23 +00:00
}
}
2021-06-23 17:20:50 +00:00
// Tor
if a.cfg.Server.Tor && a.torAddress != "" {
data.TorAddress = a.torAddress + r.RequestURI
2021-05-09 12:42:53 +00:00
}
2021-06-23 17:20:50 +00:00
if torUsed, ok := r.Context().Value(torUsedKey).(bool); ok && torUsed {
data.TorUsed = true
}
// Check if comments enabled
data.CommentsEnabled = data.Blog.Comments != nil && data.Blog.Comments.Enabled
// Check if able to receive webmentions
data.WebmentionReceivingEnabled = a.cfg.Webmention == nil || !a.cfg.Webmention.DisableReceiving
2021-07-23 10:59:24 +00:00
// Easter egg
if ee := a.cfg.EasterEgg; ee != nil && ee.Enabled {
data.EasterEgg = true
}
2021-06-23 17:20:50 +00:00
// Data
if data.Data == nil {
data.Data = map[string]interface{}{}
}
}
func (a *goBlog) includeRenderedTemplate(templateName string, data ...interface{}) (template.HTML, error) {
if l := len(data); l < 1 || l > 2 {
return "", errors.New("wrong argument count")
}
if rd, ok := data[0].(*renderData); ok {
if len(data) == 2 {
nrd := *rd
nrd.Data = data[1]
rd = &nrd
}
var buf bytes.Buffer
err := a.templates[templateName].ExecuteTemplate(&buf, templateName, rd)
return template.HTML(buf.String()), err
}
return "", errors.New("wrong arguments")
}