htmlroc/template.go

60 lines
1.2 KiB
Go

package main
import (
"html/template"
"strings"
)
var funmap = template.FuncMap{
"toCredits": tplToCredits,
"htmlify": tplHtmlify,
"toGlossary": tplToGlossary,
}
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 <br />
str = strings.ReplaceAll(str, "\n", "<br />")
return template.HTML(str)
}
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
}