mirror of
https://github.com/go-gitea/gitea.git
synced 2026-05-23 05:42:33 +09:00
chore: introduce HTMLBuilder (#37688)
This commit is contained in:
@@ -83,3 +83,34 @@ func HTMLPrintTag(w io.Writer, tag template.HTML, attrs map[string]string) (writ
|
||||
written += n
|
||||
return written, err
|
||||
}
|
||||
|
||||
func EscapeString(s string) template.HTML {
|
||||
return template.HTML(template.HTMLEscapeString(s))
|
||||
}
|
||||
|
||||
type HTMLBuilder struct {
|
||||
sb strings.Builder
|
||||
}
|
||||
|
||||
func (b *HTMLBuilder) WriteString(s string) *HTMLBuilder {
|
||||
b.sb.WriteString(template.HTMLEscapeString(s))
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *HTMLBuilder) WriteHTML(s template.HTML) *HTMLBuilder {
|
||||
b.sb.WriteString(string(s))
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *HTMLBuilder) WriteFormat(fmt template.HTML, args ...any) *HTMLBuilder {
|
||||
_, _ = HTMLPrintf(&b.sb, fmt, args...)
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *HTMLBuilder) HTMLString() template.HTML {
|
||||
return template.HTML(b.sb.String())
|
||||
}
|
||||
|
||||
func (b *HTMLBuilder) String() string {
|
||||
return b.sb.String()
|
||||
}
|
||||
|
||||
@@ -22,3 +22,10 @@ func TestHTMLFormat(t *testing.T) {
|
||||
assert.Equal(t, template.HTML("<>"), HTMLFormat("%s", template.URL("<>")))
|
||||
assert.Equal(t, template.HTML("&StringMethod &StringMethod"), HTMLFormat("%s %s", testStringer{}, &testStringer{}))
|
||||
}
|
||||
|
||||
func TestHTMLBuilder(t *testing.T) {
|
||||
b := &HTMLBuilder{}
|
||||
b.WriteString("<").WriteHTML("<hr>").WriteFormat("<span>%s%s</span>", ">", EscapeString(">"))
|
||||
assert.Equal(t, "<<hr><span>>></span>", b.String())
|
||||
assert.Equal(t, template.HTML("<<hr><span>>></span>"), b.HTMLString())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user