From 2ebab429347f04330dab9de5a730e0296ba6524b Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 8 Nov 2022 23:13:58 +0800 Subject: Move svg html render to modules/svg (#21716) Also added more checks for the render function. Co-authored-by: silverwind --- modules/svg/svg.go | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) (limited to 'modules/svg') diff --git a/modules/svg/svg.go b/modules/svg/svg.go index 1d1f8a90eb..4e13d92d41 100644 --- a/modules/svg/svg.go +++ b/modules/svg/svg.go @@ -4,10 +4,43 @@ package svg -// SVGs contains discovered SVGs -var SVGs map[string]string +import ( + "fmt" + "html/template" + "regexp" + "strings" + + "code.gitea.io/gitea/modules/html" +) + +var ( + // SVGs contains discovered SVGs + SVGs map[string]string + + widthRe = regexp.MustCompile(`width="[0-9]+?"`) + heightRe = regexp.MustCompile(`height="[0-9]+?"`) +) + +const defaultSize = 16 // Init discovers SVGs and populates the `SVGs` variable func Init() { SVGs = Discover() } + +// Render render icons - arguments icon name (string), size (int), class (string) +func RenderHTML(icon string, others ...interface{}) template.HTML { + size, class := html.ParseSizeAndClass(defaultSize, "", others...) + + if svgStr, ok := SVGs[icon]; ok { + if size != defaultSize { + svgStr = widthRe.ReplaceAllString(svgStr, fmt.Sprintf(`width="%d"`, size)) + svgStr = heightRe.ReplaceAllString(svgStr, fmt.Sprintf(`height="%d"`, size)) + } + if class != "" { + svgStr = strings.Replace(svgStr, `class="`, fmt.Sprintf(`class="%s `, class), 1) + } + return template.HTML(svgStr) + } + return template.HTML("") +} -- cgit v1.2.3