htmlroc/template.go

68 lines
1.4 KiB
Go

package main
import (
"html/template"
"strings"
)
var funmap = template.FuncMap{
"toCredits": tplToCredits,
"htmlify": tplHtmlify,
"toGlossary": tplToGlossary,
"firstLine": tplFirstLine,
}
func tplToCredits(str string) template.HTML {
// Make first line an heading
idx := strings.IndexRune(str, '\n')
if idx > 0 {
str = "<h1>" + str[:idx] + "</h1><p>" + str[idx+1:]
}
// Wrap other lines in <p> tags
str = strings.ReplaceAll(str, "\n", "</p><p>") + "</p>"
return template.HTML(str)
}
func tplHtmlify(str string) template.HTML {
// Replace newlines with paragraph blocks
str = strings.ReplaceAll(str, "\n", "</p><p>")
return template.HTML(str)
}
func tplFirstLine(str string) string {
newline := strings.IndexRune(str, '\n')
if newline < 0 {
return str
}
return str[:newline]
}
type glossaryEntry struct {
Keyword string
Definition string
}
func tplToGlossary(str string) (glob []glossaryEntry) {
lines := strings.Split(str, "\n")
for _, line := range lines {
// Skip empty lines
line = strings.TrimSpace(line)
if len(line) < 1 {
continue
}
// Find delimiter
delim := strings.IndexRune(line, ':')
if delim < 0 {
// No delim? Add to last entry
glob[len(glob)-1].Definition += line
continue
}
glob = append(glob, glossaryEntry{
Keyword: line[:delim],
Definition: strings.TrimSpace(line[delim+1:]),
})
}
return
}