This repository has been archived by the owner on Oct 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 74
/
templates.go
108 lines (93 loc) · 2.2 KB
/
templates.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//go:generate qtc --ext html
// Package templates generates and stores HTML templates
package templates
import (
"bytes"
"fmt"
"html"
"sync"
"text/template"
"github.com/bakape/meguca/common"
"github.com/bakape/meguca/config"
"github.com/bakape/meguca/lang"
)
var (
indexTemplates = make(map[string]*template.Template, 6)
mu sync.RWMutex
)
// Compile reads template HTML from disk, injects dynamic variables,
// hashes and stores them
func Compile() error {
t := make(map[string]*template.Template, len(lang.Packs))
for id := range lang.Packs {
ln := lang.Packs[id]
firstPass := renderIndex(ln)
var err error
t[id], err = template.New(ln.ID).Parse(firstPass)
if err != nil {
return err
}
}
mu.Lock()
indexTemplates = t
mu.Unlock()
return nil
}
// Board renders board page HTML for noscript browsers. withIndex specifies, if
// the rendered board page should be embedded in the index page
func Board(
b string,
ln lang.Pack,
withIndex bool,
threadHTML []byte,
) ([]byte, error) {
boardConf := config.GetBoardConfigs(b)
title := fmt.Sprintf("/%s/ - %s", b, boardConf.Title)
title = html.EscapeString(title)
html := renderBoard(threadHTML, b, title, boardConf, ln)
if !withIndex {
return []byte(html), nil
}
return execIndex(html, title, ln.ID)
}
// Thread renders thread page HTML for noscript browsers
func Thread(ln lang.Pack, withIndex bool, postHTML []byte) ([]byte, error) {
html := renderThread(postHTML, ln)
if !withIndex {
return []byte(html), nil
}
return execIndex(html, "", ln.ID)
}
// CalculateOmit returns the omitted post and image counts for a thread
func CalculateOmit(t common.Thread) (int, int) {
var (
omit = int(t.PostCtr) - len(t.Posts)
imgOmit uint32
)
if omit != 0 {
imgOmit = t.ImageCtr
if t.Image != nil {
imgOmit--
}
for _, p := range t.Posts {
if p.Image != nil {
imgOmit--
}
}
}
return omit, int(imgOmit)
}
// Execute and index template in the second pass
func execIndex(html, title, lang string) ([]byte, error) {
mu.RLock()
t := indexTemplates[lang]
mu.RUnlock()
var w bytes.Buffer
err := t.Execute(&w, struct {
Title, Threads string
}{
Title: title,
Threads: html,
})
return w.Bytes(), err
}