Refactor template render (#36438)

This commit is contained in:
wxiaoguang
2026-01-24 13:11:49 +08:00
committed by GitHub
parent 47717d4435
commit 9de659437e
31 changed files with 475 additions and 459 deletions
+3 -22
View File
@@ -10,25 +10,6 @@ import (
"unicode/utf8"
)
// ErrWrongSyntax represents a wrong syntax with a template
type ErrWrongSyntax struct {
Template string
}
func (err ErrWrongSyntax) Error() string {
return "wrong syntax found in " + err.Template
}
// ErrVarMissing represents an error that no matched variable
type ErrVarMissing struct {
Template string
Var string
}
func (err ErrVarMissing) Error() string {
return fmt.Sprintf("the variable %s is missing for %s", err.Var, err.Template)
}
// Expand replaces all variables like {var} by `vars` map, it always returns the expanded string regardless of errors
// if error occurs, the error part doesn't change and is returned as it is.
func Expand(template string, vars map[string]string) (string, error) {
@@ -66,14 +47,14 @@ func Expand(template string, vars map[string]string) (string, error) {
posBegin = posEnd
if part == "{}" || part[len(part)-1] != '}' {
// treat "{}" or "{..." as error
err = ErrWrongSyntax{Template: template}
err = fmt.Errorf("wrong syntax found in %s", template)
buf.WriteString(part)
} else {
// now we get a valid key "{...}"
key := part[1 : len(part)-1]
keyFirst, _ := utf8.DecodeRuneInString(key)
if unicode.IsSpace(keyFirst) || unicode.IsPunct(keyFirst) || unicode.IsControl(keyFirst) {
// the if key doesn't start with a letter, then we do not treat it as a var now
// if the key doesn't start with a letter, then we do not treat it as a var now
buf.WriteString(part)
} else {
// look up in the map
@@ -82,7 +63,7 @@ func Expand(template string, vars map[string]string) (string, error) {
} else {
// write the non-existing var as it is
buf.WriteString(part)
err = ErrVarMissing{Template: template, Var: key}
err = fmt.Errorf("the variable %s is missing for %s", key, template)
}
}
}