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 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题