当前位置: > > > > 将数组的索引传递给模板
将数组的索引传递给模板
来源:stackoverflow
2024-04-27 11:57:36
0浏览
收藏
有志者,事竟成!如果你在学习Golang,那么本文《将数组的索引传递给模板》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
问题内容
如何将数组的索引传递给模板? 我知道我可以这样做来访问第一个元素:
{{ with index . 0 }}
但我需要做这样的事情:
{{ template "mytemp" index . 0 }}
这似乎不起作用。我也尝试过,但没有成功:
{{ with index . 0 }}
{{ template "mytemp" . }}
{{ end }}
我似乎不知道如何实现这一目标。
解决方案
您需要 index 操作,您可以在 中阅读更多相关信息。以下是一个有效示例:
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)
}
}
这是另一个示例:
package main
import (
"os"
"text/template"
)
func main() {
data:=map[string]interface{}{ "item": []interface{}{"str1","str2"}}
tmpl, _ := template.New("test").Parse(`Some text
{{define "mytp"}}
{{.}}
{{end}}
{{template "mytp" index .item 0}}`)
tmpl.Execute(os.Stdout, data)
}
今天关于《将数组的索引传递给模板》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注米云公众号!
