range within range golang template

Mangirdas picture Mangirdas · Jul 4, 2016 · Viewed 7.1k times · Source

How to access range within range in Go templates?

Template:

{{range .Resume.Skills}}    
    {{.Name}}
    {{.Level}}
    {{range $item, $key := .Keywords}}
            {{$key}}
            {{$item}}
    {{end}}
{{end}}

Struct:

type SkillsInfo struct {
    Name     string
    Level    string
    Keywords []KeywordsInfo
}

type KeywordsInfo struct {
    Keyword string
}

result I can see is {}. How can I access Nested Objects in Templates?

---Update--:

type ResumeJson struct {
    Basics       BasicsInfo
    Work         []WorkInfo
    Volunteer    []VolunteerInfo
    Education    []EducationInfo
    Awards       []AwardsInfo
    Publications []PublicationsInfo
    Skills       []SkillsInfo
    Languages    []LaunguagesInfo
    Interests    []InterestsInfo
    References   []ReferencesInfo
}

Result seen now:

Web Development Master {} 0 {} 1 {} 2

ans JSON I parse:

 "skills": [{
    "name": "Web Development",
    "level": "Master",
    "keywords": [
         "CSS", 
         "HTML",
      "Javascript"
    ]
  }],

Answer

Cerise Limón picture Cerise Limón · Jul 4, 2016

The keywords are represented as an array of strings in the JSON. Change the Go types to match the JSON:

type SkillsInfo struct {
  Name     string
  Level    string
  Keywords []string
}

and use this template:

{{range .Resume.Skills}}    
  {{.Name}}
  {{.Level}}
  {{range .Keywords}}
     {{.}}
  {{end}}
{{end}}

playground example