我有一个 struct ,它包含一个string类型的片段,如下所示.
type Data struct {
DataFields []string
}
在我的html模板文件中,我想要覆盖字符串Slice.但是,各个字段只是没有任何 struct 名称的字符串.如何在包含简单类型(如string、int等)的片上循环?
我有一个 struct ,它包含一个string类型的片段,如下所示.
type Data struct {
DataFields []string
}
在我的html模板文件中,我想要覆盖字符串Slice.但是,各个字段只是没有任何 struct 名称的字符串.如何在包含简单类型(如string、int等)的片上循环?
或者将其分配给一个变量,类似于正常的Go range子句:
{{range $element := .DataFields}} {{$element}} {{end}}
从docs for text/template(用作html/template的界面文档):
{{range pipeline}} T1 {{end}} The value of the pipeline must be an array, slice, map, or channel. If the value of the pipeline has length zero, nothing is output; otherwise, dot is set to the successive elements of the array, slice, or map and T1 is executed. If the value is a map and the keys are of basic type with a defined order ("comparable"), the elements will be visited in sorted key order....
动作内的流水线可以初始化变量以捕获结果.初始化具有语法
$variable := pipeline
个...
如果"Range"操作初始化了一个变量,则将该变量设置为迭代的后续元素.此外,"range"可以声明两个变量,用逗号分隔:
range $index, $element := pipeline
个在这种情况下,$INDEX和$ELEMENT分别设置为数组/片索引或映射键和元素的连续值.Note that if there is only one variable, it is assigned the element; this is opposite to the convention in Go range clauses.个
(我强调的粗体部分)