小编典典

转到模板:一起使用嵌套结构的字段和{{range}}标签

go

我有以下嵌套的结构,我想在模板中的{{range .Foos}}标签中对其进行迭代。

type Foo struct {
    Field1, Field2 string
}

type NestedStruct struct {
    NestedStructID string
    Foos []Foo
}

我正在尝试使用以下html / template,但无法访问NestedStructIDfrom NestedStruct

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

golang模板有什么方法可以做我想做的事吗?


阅读 303

收藏
2020-07-02

共1个答案

小编典典

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

您可以使用$设置为传递给数据参数的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的起始值。

2020-07-02