dongshi2836 2018-06-15 20:56
浏览 31
已采纳

遍历模板切片中可变数量的项目

After searching through a fair amount of documentation and forum topics, I have not found a solution to iterating over a variable number of items in a slice using the go template engine.

My situation is as follows:

I have set up 3 structs, of which I'm passing User to an html page

type User struct {
    Name    string 
    Foos    []Foo
}

type Foo struct {
    Name        string 
    Description string 
    Bars     []Bar
}

type Bar struct {
    Name    string 
}

I would like to iterate over only the first 3 Bars in each Foo from User, but I also need to account for the possibility of each Bar containing less than 3 items.

The following will iterate over all Bars, but I only want to list up to 3, of course only listing 1 or 2 if there are only that many in the slice.

{{range .Foos}}
<div>
    <h3>{{.Name}}</h3>
    <h4>{{.Description}}</h4>
    <ol>
        {{range .Bars}}
        <li> {{.Name}} </li>
        {{end}}
    </ol>
</div>
{{end}}

Is it possible to achieve this with the go template engine? Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • doulong6761 2018-06-15 21:33
    关注

    As stated in the comments, you can trim the slice before sending it to the template, but that might be a problem if it is part of a nested struct that you need to continue using afterwards.

    Another option could be to avoid processing more than 3 elements with an if value on the index inside the loop:

    {{range $i, $val := .Bars}}
        {{if le $i 3}}<li> {{$val.Name}} </li>{{end}}
    {{end}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题