dongxuan8227 2019-03-13 03:12
浏览 18
已采纳

如何对包含在模板的结构切片中的切片进行排列?

I am trying to range over a couple of nested slices inside a template but get an error:

panic: template: abc:3: unexpected <range> in range

goroutine 1 [running]:
text/template.Must(...)
    /usr/local/go/src/text/template/helper.go:23
main.main()
    /tmp/sandbox748332064/main.go:38 +0x560

I've tried searching the docs but can't seem to figure out a workaround to being able to execute the code, even though is seems really simple.

My code:

package main

import (
    "log"
    "os"
    "text/template"
)

type Person struct {
    name     string
    children []string
}

func main() {
    p := []*Person{
      {
        name:     "Susy",
        children: []string{"Bob", "Herman", "Sherman"},
      },
      {
        name:     "Norman",
        children: []string{"Rachel", "Ross", "Chandler"},
      },
    }

    str := `
      {{$people := .}}
      {{range $i, $pp := range $people}}
        {{$children := $pp.children}}
        Name: {{$pp.name}}
        Children:
          {{range $j, $c := $children}}
          Child {{$j}}: {{$c}}
          {{end}}                   
      {{end}}
    `

    t := template.Must(template.New("abc").Parse(str))
    err := t.Execute(os.Stdout, p)
    if err != nil {
      log.Println(err)
    }

}

my playground

  • 写回答

1条回答 默认 最新

  • douben7260 2019-03-13 03:20
    关注

    Use this syntax for range:

      {{range $i, $pp := $people}}
        {{$children := $pp.Children}}
        Name: {{$pp.Name}}
        Children:
          {{range $j, $c := $children}}
          Child {{$j}}: {{$c}}
          {{end}}                   
      {{end}}
    

    Also, export the struct fields so the fields can be used by the template. Use those exported names in the template.

    Run it in the playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码