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 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决