aboutsummaryrefslogtreecommitdiffstats
path: root/filter.go
diff options
context:
space:
mode:
Diffstat (limited to 'filter.go')
-rw-r--r--filter.go39
1 files changed, 39 insertions, 0 deletions
diff --git a/filter.go b/filter.go
new file mode 100644
index 0000000..48f3e67
--- /dev/null
+++ b/filter.go
@@ -0,0 +1,39 @@
+package main
+
+import "reflect"
+
+// filterFunc returns items from a slice where the given field equals the value.
+// Template usage: {{range filter .posts "draft" false}}
+func filterFunc(items any, field string, value any) []any {
+ var result []any
+
+ rv := reflect.ValueOf(items)
+ if rv.Kind() != reflect.Slice {
+ return result
+ }
+
+ for i := 0; i < rv.Len(); i++ {
+ item := rv.Index(i)
+ if item.Kind() == reflect.Interface {
+ item = item.Elem()
+ }
+
+ var fieldVal any
+ switch item.Kind() {
+ case reflect.Map:
+ if v := item.MapIndex(reflect.ValueOf(field)); v.IsValid() {
+ fieldVal = v.Interface()
+ }
+ case reflect.Struct:
+ if f := item.FieldByName(field); f.IsValid() {
+ fieldVal = f.Interface()
+ }
+ }
+
+ if reflect.DeepEqual(fieldVal, value) {
+ result = append(result, item.Interface())
+ }
+ }
+
+ return result
+}