Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

range within range golang template

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"
    ]
  }],
like image 556
Mangirdas Avatar asked Jul 04 '16 18:07

Mangirdas


1 Answers

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

like image 195
Bayta Darell Avatar answered Oct 18 '22 19:10

Bayta Darell