go - 访问切片 Golang 模板中的结构中的特定字段
问题描述
我有这样的地方我发送到模板年数据(这是结构的切片)。如何AcaYear
仅访问第二项(结构)的模板侧字段?整个第二项我可以访问为{{index . 1 }}
. 我还可以在切片上进行范围并获取AcaYear
所有项目的字段。但只需要AcaYear
第二项的字段(结果应该是2021-2022
)。
package main
import (
"log"
"os"
"text/template"
)
type course struct {
Number string
Name string
Units string
}
type semester struct {
Term string
Courses []course
}
type year struct {
AcaYear string
Fall semester
Spring semester
Summer semester
}
var tpl *template.Template
func init() {
tpl = template.Must(template.ParseFiles("tpl.gohtml"))
}
func main() {
years := []year{
year{
AcaYear: "2020-2021",
Fall: semester{
Term: "Fall",
Courses: []course{
course{"CSCI-40", "Introduction to Programming in Go", "4"},
course{"CSCI-130", "Introduction to Web Programming with Go", "4"},
course{"CSCI-140", "Mobile Apps Using Go", "4"},
},
},
Spring: semester{
Term: "Spring",
Courses: []course{
course{"CSCI-50", "Advanced Go", "5"},
course{"CSCI-190", "Advanced Web Programming with Go", "5"},
course{"CSCI-191", "Advanced Mobile Apps With Go", "5"},
},
},
},
year{
AcaYear: "2021-2022",
Fall: semester{
Term: "Fall",
Courses: []course{
course{"CSCI-40", "Introduction to Programming in Go", "4"},
course{"CSCI-130", "Introduction to Web Programming with Go", "4"},
course{"CSCI-140", "Mobile Apps Using Go", "4"},
},
},
Spring: semester{
Term: "Spring",
Courses: []course{
course{"CSCI-50", "Advanced Go", "5"},
course{"CSCI-190", "Advanced Web Programming with Go", "5"},
course{"CSCI-191", "Advanced Mobile Apps With Go", "5"},
},
},
},
}
err := tpl.Execute(os.Stdout, years)
if err != nil {
log.Fatalln(err)
}
}
解决方案
推荐阅读
- sql - 未定义类型的案例语句?或为什么约会?
- php - 接受协议中的任何数字类似
- c++ - C++;如何在函数中写入opencv的Vect3b指针
- php - 无法从表名中的大写字母替换为小写字母的 mySQL 表中读取数据 (PHP) (Wo_Langs -> wo_langs)
- c - 如何获取 *chars 并返回非整数?
- javascript - 有一种方法可以解决“警告:列表中的每个孩子都应该有一个唯一的“键”?
- powerbi - Power BI:计算列中的多个值
- javascript - 如何根据其他数组更改原始数组
- blockchain - 锯齿交易家族互动
- java - 将 react 本机应用程序与联系人集成