1

I have the following nested struct and I would like to iterate them in a template, in a {{range .Foos}} tag.

type Foo struct {
    Field1, Field2 string
}

type NestedStruct struct {
    NestedStructID string
    Foos []Foo
}

I'm trying with the following html/template but it can't access the NestedStructID from NestedStruct.

{{range .Foos}} { source: '{{.Field1}}', target: '{{.NestedStructID}}' }{{end}}

Is there any way with golang templates to do what I'd like to do?

4

1 回答 1

3

您无法NestedStructID像这样到达该字段,因为该{{range}}操作将每次迭代中的管道(点.)设置为当前元素。

您可以使用$which 设置为传递给的数据参数Template.Execute();所以如果你传递一个值NestedStruct,你可以使用$.NestedStructID.

例如:

func main() {
    t := template.Must(template.New("").Parse(x))

    ns := NestedStruct{
        NestedStructID: "nsid",
        Foos: []Foo{
            {"f1-1", "f2-1"},
            {"f1-2", "f2-2"},
        },
    }
    fmt.Println(t.Execute(os.Stdout, ns))
}

const x = `{{range .Foos}}{ source: '{{.Field1}}', target: '{{$.NestedStructID}}' }
{{end}}`

输出(在Go Playground上试试):

{ source: 'f1-1', target: 'nsid' }
{ source: 'f1-2', target: 'nsid' }
<nil>

这记录在text/template

开始执行时,$ 设置为传递给 Execute 的数据参数,即设置为 dot 的起始值。

于 2017-02-03T10:52:42.893 回答