feat: substitute placeholders and escape text

This commit is contained in:
tgiachi 2026-11-15 09:42:13 +01:00
commit 27dac18c8f
2 changed files with 124 additions and 0 deletions

50
internal/render/render.go Normal file
View file

@ -0,0 +1,50 @@
// 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)
}

View file

@ -0,0 +1,74 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package render
import (
"strings"
"testing"
)
// TestSubstituteKnown checks that known placeholders are replaced everywhere.
func TestSubstituteKnown(t *testing.T) {
ctx := map[string]string{"name": "kmalloc", "tld_1": "org"}
got, err := Substitute("page.html", "<p>{{name}}.{{tld_1}} and {{name}}</p>", ctx)
if err != nil {
t.Fatalf("Substitute() error = %v", err)
}
if want := "<p>kmalloc.org and kmalloc</p>"; got != want {
t.Errorf("Substitute() = %q, want %q", got, want)
}
}
// TestSubstituteUnknownNamesFile checks that an unknown placeholder stops the
// build and names both the file and the placeholder.
func TestSubstituteUnknownNamesFile(t *testing.T) {
_, err := Substitute("news/post.md", "Hello {{nope}}", map[string]string{})
if err == nil {
t.Fatal("Substitute() error = nil")
}
for _, want := range []string{"news/post.md", "nope"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("error %q does not contain %q", err, want)
}
}
}
// TestSubstituteLeavesNonPlaceholders checks that braces that do not form a
// placeholder are left as written, so articles can show template code.
func TestSubstituteLeavesNonPlaceholders(t *testing.T) {
for _, in := range []string{"{{.Name}}", "{{ spaced }}", "{{UPPER}}", "{{a-b}}", "{single}", "{{}}"} {
got, err := Substitute("f", in, map[string]string{})
if err != nil {
t.Errorf("Substitute(%q) error = %v", in, err)
}
if got != in {
t.Errorf("Substitute(%q) = %q, want it unchanged", in, got)
}
}
}
// TestSubstituteValueIsNotRescanned checks that a replaced value is inserted
// as is and its own braces are not substituted again.
func TestSubstituteValueIsNotRescanned(t *testing.T) {
got, err := Substitute("f", "{{a}}", map[string]string{"a": "{{b}}", "b": "x"})
if err != nil {
t.Fatal(err)
}
if got != "{{b}}" {
t.Errorf("Substitute() = %q, want %q", got, "{{b}}")
}
}
// TestEscape checks that text escaping leaves quotes alone.
func TestEscape(t *testing.T) {
if got, want := Escape(`a & b < c > "d" 'e'`), `a &amp; b &lt; c &gt; "d" 'e'`; got != want {
t.Errorf("Escape() = %q, want %q", got, want)
}
}
// TestEscapeAttr checks that attribute escaping also covers both quotes.
func TestEscapeAttr(t *testing.T) {
if got, want := EscapeAttr(`a & "b" 'c' <d>`), `a &amp; &quot;b&quot; &#x27;c&#x27; &lt;d&gt;`; got != want {
t.Errorf("EscapeAttr() = %q, want %q", got, want)
}
}