Skip to content

Instantly share code, notes, and snippets.

@morrxy
Last active February 27, 2022 22:42
Show Gist options
  • Save morrxy/06fb44e967ba5c8b4b59f08268f9dd73 to your computer and use it in GitHub Desktop.
Save morrxy/06fb44e967ba5c8b4b59f08268f9dd73 to your computer and use it in GitHub Desktop.
[template check field exists] #golang
//https://stackoverflow.com/a/19294004/1215930
type Data []interface{}
func (p Data) HasField(name string, value interface{}) bool {
for _, v := range p {
if m, ok := v.(map[string]interface{}); !ok {
return false
} else if _, ok := m[name]; ok && reflect.DeepEqual(m[name], value) {
return true
}
}
return false
}
{{$hasFemale := .HasField "sex" "F"}}
{{if $hasFemale}}Female:
{{range .}}{{if eq .sex "F"}}{{.name}}{{end}}{{end}}
{{end}}`
//https://stackoverflow.com/questions/34703133/field-detection-in-go-html-template
func hasField(v interface{}, name string) bool {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
return false
}
return rv.FieldByName(name).IsValid()
}
{{if hasField . "FieldA"}}<a>{{.FieldA}}</a>{{end}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment