【问题标题】:range within range golang template范围内的范围 golang 模板
【发布时间】:2016-11-06 12:49:40
【问题描述】:

如何在 Go 模板中访问范围内的范围?

模板:

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

结构:

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

type KeywordsInfo struct {
    Keyword string
}

我可以看到的结果是 {}。如何访问模板中的嵌套对象?

---更新--:

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

现在看到的结果:

网页开发大师{} 0 {} 1 {} 2

我解析的 JSON:

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

【问题讨论】:

  • 我感觉这可能是由于我阅读了 json (更新)。但不知道为什么会这样
  • 模板没有错误。但现在我开始考虑它的 JSON 或 Revel 框架以及它们如何实现模板

标签: go revel go-templates


【解决方案1】:

关键字在 JSON 中表示为字符串数组。更改 Go 类型以匹配 JSON:

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

并使用此模板:

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

playground example

【讨论】:

    猜你喜欢
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2021-02-28
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2017-03-16
    相关资源
    最近更新 更多