gpt4 book ai didi

go - 模板中数组索引的范围

转载 作者:IT王子 更新时间:2023-10-29 01:16:25 27 4
gpt4 key购买 nike

我知道你可以在范围内使用索引:

{{range $i, $e := .First}}$e - {{index $.Second $i}}{{end}}

发件人:how to use index inside range in html/template to iterate through parallel arrays?

如果索引还包含一个数组,我该如何遍历索引?

例如。

type a struct {
Title []string
Article [][]string
}
IndexTmpl.ExecuteTemplate(w, "index.html", a)

index.html

{{range $i, $a := .Title}}
{{index $.Article $i}} // Want to range over this.
{{end}}

最佳答案

您可以使用嵌套循环,就像您在编写代码时一样。

这里有一些代码证明了这一点,also available on the playground .

package main

import (
"html/template"
"os"
)

type a struct {
Title []string
Article [][]string
}

var data = &a{
Title: []string{"One", "Two", "Three"},
Article: [][]string{
[]string{"a", "b", "c"},
[]string{"d", "e"},
[]string{"f", "g", "h", "i"}},
}

var tmplSrc = `
{{range $i, $a := .Title}}
Title: {{$a}}
{{range $article := index $.Article $i}}
Article: {{$article}}.
{{end}}
{{end}}`

func main() {
tmpl := template.Must(template.New("test").Parse(tmplSrc))
tmpl.Execute(os.Stdout, data)
}

关于go - 模板中数组索引的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29762118/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com