aboutsummaryrefslogtreecommitdiffstats
path: root/filter.go
blob: 2f855fe7cb62cec92e250cbd8f0c958560cda8f6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
}