golang 模板中字符串切片的范围

Range over string slice in golang template

我有一个结构,其中包含如下所示的一段字符串类型。

 type Data struct {
      DataFields []string
 }

在我的 html 模板文件中,我想遍历字符串切片。但是,各个字段只是没有任何结构名称的字符串。如何遍历包含简单类型(如字符串、整数等)的切片?

使用 . 来引用简单的值,如字符串、整数等

 {{range .DataFields}}{{.}}{{end}}

Run it on the Playground.

您也可以像 {{range $v := .DataFields}}{{$v}}{{end}} 那样分配给模板变量,但这是额外的工作。拥抱 ..

或者把它赋给一个变量,类似于普通的 Go range 子句:

 {{range $element := .DataFields}} {{$element}} {{end}}

Run it on the Playground

来自 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.

...

A pipeline inside an action may initialize a variable to capture the result. The initialization has syntax

$variable := pipeline

...

If a "range" action initializes a variable, the variable is set to the successive elements of the iteration. Also, a "range" may declare two variables, separated by a comma:

range $index, $element := pipeline

in which case $index and $element are set to the successive values of the array/slice index or map key and element, respectively. Note that if there is only one variable, it is assigned the element; this is opposite to the convention in Go range clauses.

(bold portions emphasized by me)