Skip to content

Instantly share code, notes, and snippets.

@linhmtran168
Created April 8, 2019 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linhmtran168/eb7f62213edc4d44c6879fa2734c5bb2 to your computer and use it in GitHub Desktop.
Save linhmtran168/eb7f62213edc4d44c6879fa2734c5bb2 to your computer and use it in GitHub Desktop.
Pongo2 filter using reflect
// TrueCondition implement IConditionCheckable interface
func (test *TestStruct) TrueCondition() bool {
if test.IsTrue {
return true
}
return false
}
// 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