Last active
February 27, 2022 22:42
-
-
Save morrxy/06fb44e967ba5c8b4b59f08268f9dd73 to your computer and use it in GitHub Desktop.
[template check field exists] #golang
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
//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}}` |
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
//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