转到模板:一起使用嵌套结构的字段和{{range}}标签 [英] Go Template : Use nested struct's field and {{range}} tag together

查看:201
本文介绍了转到模板:一起使用嵌套结构的字段和{{range}}标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

我正在尝试使用以下html/template,但它无法从NestedStruct访问NestedStructID.

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

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

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

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

推荐答案

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

You can't reach the NestedStructID field like that because the {{range}} action sets the pipeline (the dot .) in each iteration to the current element.

您可以使用$,该参数设置为传递给Template.Execute()的数据参数;因此,如果您传递值NestedStruct,则可以使用$.NestedStructID.

You may use the $ which is set to the data argument passed to Template.Execute(); so if you pass a value of NestedStruct, you can use $.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}}`

输出(在游乐场上尝试):

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

此文档记录在 text/template :

This is documented in text/template:

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

When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

这篇关于转到模板:一起使用嵌套结构的字段和{{range}}标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆