How do you pass structs to subtemplates in go?

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

How do you pass structs to subtemplates in go?

问题

我正在尝试理解如何在Go中多次使用相同的模板,传递不同的结构体。

这是我尝试过的代码:

import (
	"fmt"
	"html/template"
	"os"
)

type person struct {
	id    int
	name  string
	phone string
}

type page struct {
	p1 person
	p2 person
}

func main() {
	p1 := person{1, "Peter", "1001"}
	p2 := person{2, "Mary", "1002"}
	p := page{p1, p2}

	fmt.Println(p)

	t := template.Must(template.New("foo").Parse(`
	{{define "s1"}}
	<span id="{{.id}}">{{.name}} {{.phone}}</span>
	{{end}}
	{{template "s1" .p1}}{{template "s1" .p2}}
	`))

	t.Execute(os.Stdout, p)
}

但它没有按预期工作:

panic: template: foo:5: unexpected "{" in template clause

预期的输出是:

Peter 1001Mary 1002

英文:

I am trying to understand how to use the same template in Go several time passing different structs.

This is what I have tried:

import (
	&quot;fmt&quot;
	&quot;html/template&quot;
	&quot;os&quot;
)

type person struct {
	id    int
	name  string
	phone string
}

type page struct {
	p1 person
	p2 person
}

func main() {
	p1 := person{1, &quot;Peter&quot;, &quot;1001&quot;}
	p2 := person{2, &quot;Mary&quot;, &quot;1002&quot;}
	p := page{p1, p2}

	fmt.Println(p)

	t := template.Must(template.New(&quot;foo&quot;).Parse(`
	{{define &quot;s1&quot;}}
	&lt;span id=&quot;{{.id}}&quot;&gt;{{.name}} {{.phone}}&lt;/span&gt;
	{{end}}
	{{template &quot;s1&quot; {{.p1}}}}{{template &quot;s1&quot; {{.p2}}}}
	`))

	t.Execute(os.Stdout, p)
}

But it does not work as expected:

panic: template: foo:5: unexpected &quot;{&quot; in template clause

The expected output is:

&lt;span id=&quot;1&quot;&gt;Peter 1001&lt;/span&gt;&lt;span id=&quot;2&quot;&gt;Mary 1002&lt;/span&gt;

答案1

得分: 2

当你调用模板函数时,你需要提供两个参数(用空格分隔):

  • 一个已定义的模板名称("s1")
  • 你的对象:在你的情况下是.p1

所以这是一个适用于你的工作模板:

	t := template.Must(template.New("foo").Parse(`
    {{ define "s1" }}
        <span id="{{ .id }}">{{.name}} {{ .phone }}</span>
    {{ end }}

    {{ template "s1" .p1 }}
    {{ template "s1" .p2 }}
    `))
}
英文:

When you call the template function, you give 2 arguments (separated by a space):

  • A defined template name ("s1")
  • You object: .p1 in your case

So here is a working template in your case:

	t := template.Must(template.New(&quot;foo&quot;).Parse(`
    {{ define &quot;s1&quot; }}
        &lt;span id=&quot;{{ .id }}&quot;&gt;{{.name}} {{ .phone }}&lt;/span&gt;
    {{ end }}

    {{ template &quot;s1&quot; .p1 }}
    {{ template &quot;s1&quot; .p2 }}
    `))
}

huangapple
  • 本文由 发表于 2022年4月30日 21:52:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/72069079.html
匿名

发表评论

匿名网友

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

确定