Created
April 8, 2019 10:37
-
-
Save linhmtran168/eb7f62213edc4d44c6879fa2734c5bb2 to your computer and use it in GitHub Desktop.
Pongo2 filter using reflect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// TrueCondition implement IConditionCheckable interface | |
func (test *TestStruct) TrueCondition() bool { | |
if test.IsTrue { | |
return true | |
} | |
return false | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// IConditionCheckable interface for every type that have function to return true condition | |
type IConditionCheckable interface { | |
TrueCondition() bool | |
} | |
// FilterTrueCondition pongo2 filter to check if there is a value in the map return true for a condition | |
func FilterTrueCondition(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) { | |
inValue := reflect.ValueOf(in.Interface()) | |
if inValue.Kind() != reflect.Map { | |
return nil, &pongo2.Error{Sender: "filter:trueCondition"} | |
} | |
for _, k := range inValue.MapKeys() { | |
v := inValue.MapIndex(k) | |
mapVal := v.Interface() | |
if rv, ok := mapVal.(IConditionCheckable); ok { | |
if rv.TrueCondition() { | |
return pongo2.AsValue(true), nil | |
} | |
} | |
} | |
return pongo2.AsValue(false), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment