给定一组结构,我如何使用“范围”模板迭代器打印出一个表,该表为每个结构分配一行,为每个字段值分配一列,而不显式命名字段?
container := []Node
type Node struct {
Contact_id int
Employer_id int
First_name string
Middle_name string
Last_name string
}
模板代码:
{{range .container}}
<tr>
<td>{{.Prefix}}</td>
<td>{{.First_name}}</td>
<td>{{.Middle_name}}</td>
<td>{{.Last_name}}</td>
<td>{{.Contact_id}}</td>
<td>{{.Employer_id}}</td>
</tr>
{{end}}
当我尝试使用
遍历值时{{range .container}}
{{range .}}
<td>{{.}}</td>
{{end}}
{{end}}
我被告知我无法迭代这些值。 有什么干净的方法可以做到这一点吗?
最佳答案
使用 html/template
,您不能遍历结构中的字段。在documentation对于包,你可以阅读:
{{range pipeline}} T1 {{end}}
The value of the pipeline must be an array, slice, map, or channel.
也就是说,Pipeline 不能是结构体。您需要:
- 使用中间类型,例如。
[][]interface{}
,作为传递给模板的容器变量 - 按照您显示的方式分别输入每个单元格
- 创建一个模板函数,将结构值转换为可以迭代的某种类型
由于结构是在编译时定义的,不会在运行时更改其结构,因此不需要迭代,也不会使模板中的内容更加清晰。我建议不要这样做。
编辑
但有时反射(reflection)是件好事。 Brenden 还指出,您实际上可以让 range 遍历函数返回的值。如果使用反射,这将是最简单的方法。
使用模板函数的完整工作示例:
package main
import (
"html/template"
"os"
"reflect"
)
type Node struct {
Contact_id int
Employer_id int
First_name string
Middle_name string
Last_name string
}
var templateFuncs = template.FuncMap{"rangeStruct": RangeStructer}
// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range .}}<tr>
{{range rangeStruct .}} <td>{{.}}</td>
{{end}}</tr>
{{end}}`
func main() {
container := []Node{
{1, 12, "Accipiter", "ANisus", "Nisus"},
{2, 42, "Hello", "my", "World"},
}
// We create the template and register out template function
t := template.New("t").Funcs(templateFuncs)
t, err := t.Parse(htmlTemplate)
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, container)
if err != nil {
panic(err)
}
}
// RangeStructer takes the first argument, which must be a struct, and
// returns the value of each field in a slice. It will return nil
// if there are no arguments or first argument is not a struct
func RangeStructer(args ...interface{}) []interface{} {
if len(args) == 0 {
return nil
}
v := reflect.ValueOf(args[0])
if v.Kind() != reflect.Struct {
return nil
}
out := make([]interface{}, v.NumField())
for i := 0; i < v.NumField(); i++ {
out[i] = v.Field(i).Interface()
}
return out
}
输出:
<tr>
<td>1</td>
<td>12</td>
<td>Accipiter</td>
<td>ANisus</td>
<td>Nisus</td>
</tr>
<tr>
<td>2</td>
<td>42</td>
<td>Hello</td>
<td>my</td>
<td>World</td>
</tr>
关于html - Go template/html 迭代从结构生成表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19991124/