gitea源码

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package htmlutil
  4. import (
  5. "fmt"
  6. "html/template"
  7. "slices"
  8. "strings"
  9. )
  10. // ParseSizeAndClass get size and class from string with default values
  11. // If present, "others" expects the new size first and then the classes to use
  12. func ParseSizeAndClass(defaultSize int, defaultClass string, others ...any) (int, string) {
  13. size := defaultSize
  14. if len(others) >= 1 {
  15. if v, ok := others[0].(int); ok && v != 0 {
  16. size = v
  17. }
  18. }
  19. class := defaultClass
  20. if len(others) >= 2 {
  21. if v, ok := others[1].(string); ok && v != "" {
  22. if class != "" {
  23. class += " "
  24. }
  25. class += v
  26. }
  27. }
  28. return size, class
  29. }
  30. func HTMLFormat(s template.HTML, rawArgs ...any) template.HTML {
  31. if !strings.Contains(string(s), "%") || len(rawArgs) == 0 {
  32. panic("HTMLFormat requires one or more arguments")
  33. }
  34. args := slices.Clone(rawArgs)
  35. for i, v := range args {
  36. switch v := v.(type) {
  37. case nil, bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, template.HTML:
  38. // for most basic types (including template.HTML which is safe), just do nothing and use it
  39. case string:
  40. args[i] = template.HTMLEscapeString(v)
  41. case template.URL:
  42. args[i] = template.HTMLEscapeString(string(v))
  43. case fmt.Stringer:
  44. args[i] = template.HTMLEscapeString(v.String())
  45. default:
  46. args[i] = template.HTMLEscapeString(fmt.Sprint(v))
  47. }
  48. }
  49. return template.HTML(fmt.Sprintf(string(s), args...))
  50. }