1
1
mirror of https://github.com/go-gitea/gitea synced 2025-07-22 18:28:37 +00:00

Make template Iif exactly match if (#31322)

This commit is contained in:
wxiaoguang
2024-06-11 22:52:12 +08:00
committed by GitHub
parent 61c97fdef1
commit 4bf848a06b
2 changed files with 47 additions and 21 deletions

View File

@@ -239,7 +239,7 @@ func DotEscape(raw string) string {
// Iif is an "inline-if", similar util.Iif[T] but templates need the non-generic version,
// and it could be simply used as "{{Iif expr trueVal}}" (omit the falseVal).
func Iif(condition any, vals ...any) any {
if IsTruthy(condition) {
if isTemplateTruthy(condition) {
return vals[0]
} else if len(vals) > 1 {
return vals[1]
@@ -247,7 +247,7 @@ func Iif(condition any, vals ...any) any {
return nil
}
func IsTruthy(v any) bool {
func isTemplateTruthy(v any) bool {
if v == nil {
return false
}
@@ -256,20 +256,20 @@ func IsTruthy(v any) bool {
switch rv.Kind() {
case reflect.Bool:
return rv.Bool()
case reflect.String:
return rv.String() != ""
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return rv.Int() != 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return rv.Uint() != 0
case reflect.Float32, reflect.Float64:
return rv.Float() != 0
case reflect.Slice, reflect.Array, reflect.Map:
case reflect.Complex64, reflect.Complex128:
return rv.Complex() != 0
case reflect.String, reflect.Slice, reflect.Array, reflect.Map:
return rv.Len() > 0
case reflect.Ptr:
return !rv.IsNil() && IsTruthy(reflect.Indirect(rv).Interface())
case reflect.Struct:
return true
default:
return rv.Kind() == reflect.Struct && !rv.IsNil()
return !rv.IsNil()
}
}