Go模板:同时使用嵌套结构的字段和{{range}}标签

huangapple go评论87阅读模式
英文:

Go Template : Use nested struct's field and {{range}} tag together

问题

我有以下嵌套结构体,我想在模板中使用{{range .Foos}}标签来迭代它们。

type Foo struct {
    Field1, Field2 string
}

type NestedStruct struct {
    NestedStructID string
    Foos []Foo
}

我尝试使用以下html/template,但它无法访问NestedStruct中的NestedStructID

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

在golang模板中有没有办法实现我想要的效果?

英文:

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?

答案1

得分: 3

你不能像那样访问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的初始值。

英文:

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.

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.

For example:

func main() {
	t := template.Must(template.New(&quot;&quot;).Parse(x))

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

const x = `{{range .Foos}}{ source: &#39;{{.Field1}}&#39;, target: &#39;{{$.NestedStructID}}&#39; }
{{end}}`

Output (try it on the Go Playground):

{ source: &#39;f1-1&#39;, target: &#39;nsid&#39; }
{ source: &#39;f1-2&#39;, target: &#39;nsid&#39; }
&lt;nil&gt;

This is documented in text/template:

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

huangapple
  • 本文由 发表于 2017年2月3日 18:44:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/42022392.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定