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

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

报告相同问题?

悬赏问题

  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)