dsi37923 2019-08-27 02:07
浏览 11
已采纳

将数组的索引传递给模板

How can I pass the index of an array to a template? I know I can do something like this to access the first element:

{{ with index . 0 }}

but I need to do something like this:

{{ template "mytemp" index . 0 }}

which doesn't seem to work. I also tried this which didn't work:

{{ with index . 0 }}
  {{ template "mytemp" . }}
{{ end }}

I can't seem to figure out how to achieve this.

  • 写回答

2条回答 默认 最新

  • drrvnbwle80177811 2019-08-27 02:52
    关注

    You need the index action, you can read more about it in the documentation. Here is a working example:

    package main
    
    import (
        "log"
        "os"
        "text/template"
    )
    
    type Inventory struct {
        Material []string
        Count    uint
    }
    
    func main() {
        sweaters := Inventory{[]string{"wool"}, 17}
        tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{index .Material 0}}")
        if err != nil {
            log.Fatal(err)
        }
        err = tmpl.Execute(os.Stdout, sweaters)
        if err != nil {
            log.Fatal(err)
        }
    
    }
    

    Go Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题