motorino/internal/render/render.go

50 lines
1.6 KiB
Go

// SPDX-License-Identifier: GPL-3.0-or-later
// Package render replaces the {{name}} placeholders of templates and page
// sources and escapes text for HTML.
package render
import (
"fmt"
"regexp"
"strings"
)
// placeholder matches {{name}} where name is lowercase letters, digits and
// underscores. Braces that do not match, such as {{.Name}}, are plain text.
var placeholder = regexp.MustCompile(`\{\{([a-z0-9_]+)\}\}`)
// Substitute replaces every {{name}} in tmpl with ctx[name]. An unknown name
// is an error that names the file and the placeholder. Values are inserted as
// they are and are not scanned again.
func Substitute(name, tmpl string, ctx map[string]string) (string, error) {
var missing string
out := placeholder.ReplaceAllStringFunc(tmpl, func(match string) string {
key := match[2 : len(match)-2]
value, ok := ctx[key]
if !ok && missing == "" {
missing = key
}
return value
})
if missing != "" {
return "", fmt.Errorf("%s: unknown placeholder {{%s}}", name, missing)
}
return out, nil
}
// textEscaper escapes the characters that matter in HTML text.
var textEscaper = strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;")
// attrEscaper also escapes both kinds of quote, for attribute values.
var attrEscaper = strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;", `"`, "&quot;", "'", "&#x27;")
// Escape escapes &, < and > for use in HTML text. Quotes are left alone.
func Escape(s string) string {
return textEscaper.Replace(s)
}
// EscapeAttr escapes &, <, > and both quotes for use in an HTML attribute.
func EscapeAttr(s string) string {
return attrEscaper.Replace(s)
}