Refactor Safe modifier (#29392)

After this PR: no need to play with the Safe/Escape tricks anymore. See
the changes for more details.

(cherry picked from commit f9207b09479df964872d68842469991042b5497f)

Conflicts:
	templates/repo/issue/view_title.tmpl
	templates/user/settings/applications.tmpl
	context
This commit is contained in:
wxiaoguang 2024-02-25 18:45:56 +08:00 committed by Earl Warren
parent 30fe3d8d4c
commit 90a62b87c0
No known key found for this signature in database
GPG key ID: 0579CB2928A78A00
24 changed files with 79 additions and 55 deletions

View file

@ -9,6 +9,7 @@ import (
"html"
"html/template"
"net/url"
"slices"
"strings"
"time"
@ -34,7 +35,8 @@ func NewFuncMap() template.FuncMap {
// html/template related functions
"dict": dict, // it's lowercase because this name has been widely used. Our other functions should have uppercase names.
"Eval": Eval,
"Safe": Safe,
"SafeHTML": SafeHTML,
"HTMLFormat": HTMLFormat,
"Escape": Escape,
"QueryEscape": url.QueryEscape,
"JSEscape": JSEscapeSafe,
@ -180,8 +182,25 @@ func NewFuncMap() template.FuncMap {
}
}
// Safe render raw as HTML
func Safe(s any) template.HTML {
func HTMLFormat(s string, rawArgs ...any) template.HTML {
args := slices.Clone(rawArgs)
for i, v := range args {
switch v := v.(type) {
case nil, bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, template.HTML:
// for most basic types (including template.HTML which is safe), just do nothing and use it
case string:
args[i] = template.HTMLEscapeString(v)
case fmt.Stringer:
args[i] = template.HTMLEscapeString(v.String())
default:
args[i] = template.HTMLEscapeString(fmt.Sprint(v))
}
}
return template.HTML(fmt.Sprintf(s, args...))
}
// SafeHTML render raw as HTML
func SafeHTML(s any) template.HTML {
switch v := s.(type) {
case string:
return template.HTML(v)