我有一个 struct ,它包含一个string类型的片段,如下所示.

 type Data struct {
      DataFields []string
 }

在我的html模板文件中,我想要覆盖字符串Slice.但是,各个字段只是没有任何 struct 名称的字符串.如何在包含简单类型(如string、int等)的片上循环?

推荐答案

或者将其分配给一个变量,类似于正常的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.

...

动作内的流水线可以初始化变量以捕获结果.初始化具有语法

$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.

(我强调的粗体部分)

Go相关问答推荐

语法-for循环中的initit陈述是否允许分配?

Golang String

Date.Format正在输出非常奇怪的日期

将这两个函数合二为一的惯用方法

死锁 - 所有 goroutine 都处于睡眠状态(即使使用等待组)

正则表达式模式,确保至少一个字符与其他条件一起存在

Go Template 动态获取变量

使用Dockertest进行Golang SQL单元测试的基本设置

如何将Golang测试用例的测试覆盖率值与特定阈值进行比较

如何解决我的 Go 聊天应用程序中 cookie 未在本地主机端口之间传输的问题?

你如何在 Golang 代码中测试 filepath.Abs​​ 失败?

helm :将 YAML 转换为 JSON 时出错:yaml:第 xx 行:未找到预期的密钥

致命错误 - 所有 Goroutines 都睡着了!僵局

Go:从 ssl 证书中获取 'subject/unstructeredName' 的值

Dockerfile 问题 - 为什么找不到二进制 dlv - 没有这样的文件或目录

Gorm 在保存/创建时序列化 struct

如何在gin中获取参数值数组

函数调用中的类型参数panic

Go Flag 用法 描述 包含 Word 值

是否存在一个Go泛型类型约束,该约束捕获了将类型用作映射中的键的能力?