range within range golang template
Asked Answered
O

1

11

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"
    ]
  }],
Orthopter answered 4/7, 2016 at 18:41 Comment(3)
I have a feeling it may be due json I read (updated). But no idea whyit behaves like thisOrthopter
There is no error from template. But now i start thinking its either JSON or Revel framework and how they implemented templatesOrthopter
Inner range values should be reversed: range $key, $value := .Keywords.Untread
R
14

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

Radix answered 4/7, 2016 at 19:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.