Check if value exists in nested array with template package

Using text/template, I need to find out if any object in the array has a specific property value.

Let's say I have a list of people (json):

[
    {"name": "ANisus", "sex":"M"},
    {"name": "Sofia", "sex":"F"},
    {"name": "Anna", "sex":"F"}
]

Using the template, I want to get this output:

Females:
Sofia
Anna

But the title Females:should only be displayed if there really is a person with sexinstalled on F. How can I accomplish this in a template system? My first attempt was to use a variable:

{{$hasFemale := 0}}
{{range .}}{{if eq .sex "F"}}{{$hasFemale := 1}}{{end}}{{end}}
{{if $hasFemale}}Female:{{end}}

I was not able to get this to work because $ hasFemale within the range is in a different scope and does not match the one that was initiated with 0. I cannot find a way to change the variable being initiated.

" ": http://play.golang.org/p/T-Ekx7n9YQ

; .

+4
1

-. , , .

, , HasFemales . , , ( ):

type People []interface{}

func (p People) HasFemale() bool {
    for _, v := range p {
        if m, ok := v.(map[string]interface{}); !ok {
            return false
        } else if _, ok := m["sex"]; ok && m["sex"] == "F" {
            return true
        }
    }
    return false
}

:

{{if .HasFemale}}Female:
    {{range .}}{{if eq .sex "F"}}{{.name}}{{end}}{{end}}
{{end}}

, , , , , , , encoding/json . .HasFemale , .

:

Go, : 1) 2) json. . wkhtmltopdf pdf. / , Go

HasFemale . , , , . :

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}}`
+4

All Articles