Golang中如何在定义模板中传递值

Golang中如何在定义模板中传递值 我创建了一个包含“define”块(即“t1”)的 text/template。该“define”块期望一个名为 Name 的变量。我在主模板中使用了这个“t1”。我传递了变量 Name 的值,它在 t1 中显示为 <no value>,而在主模板中却能显示该值。

package main

import (
	"log"
	"os"
	"text/template"
)

const tmptTxt = `
{{- define "t1" }} {{.Name}} the first tempalte {{ end -}}
{{template "t1"}}
{{ .Name }}
`

func main() {
	t, err := template.New("temp").Parse(tmptTxt)
	if err != nil {
		log.Fatal(err)
	}
	t.Execute(os.Stdout, person{Name: "Prithvi"})
}

type person struct {
	Name string
}

输出

 <no value> the first tempalte
Prithvi

如何从主模板向代码中的 {{- define "t1" }} {{.Name}} the first tempalte {{ end -}} 传递值?


更多关于Golang中如何在定义模板中传递值的实战教程也可以访问 https://www.itying.com/category-94-b0.html

5 回复

很好

更多关于Golang中如何在定义模板中传递值的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


我正在学习如何在 {{- define "t1" }} {{.Name}} the first template {{ end -}} 中传递值。我遇到了问题。我知道如何向普通模板传递值。

func main() {
    fmt.Println("hello world")
}

我找到了解决方案。在调用模板时,我忘记使用点号(.)传递值。以下是修复后的模板文本:

const tmptTxt = `
{{- define "t1" }} {{.Name}} the first tempalte {{ end -}}
{{template "t1" .}}
{{ .Name }}
`

请查看你的模板,参考以下示例

Go Playground - The Go Programming Language

Go Playground - The Go Programming Language

在Go的text/template中,当你使用{{template "t1"}}调用已定义的模板时,需要显式传递当前作用域的数据。默认情况下,如果不指定第二个参数,模板会继承当前作用域。但在你的代码中,{{template "t1"}}没有传递参数,导致t1模板无法访问到.Name

以下是修正后的代码:

package main

import (
	"log"
	"os"
	"text/template"
)

const tmptTxt = `
{{- define "t1" }} {{.Name}} the first template {{ end -}}
{{template "t1" .}}
{{ .Name }}
`

func main() {
	t, err := template.New("temp").Parse(tmptTxt)
	if err != nil {
		log.Fatal(err)
	}
	t.Execute(os.Stdout, person{Name: "Prithvi"})
}

type person struct {
	Name string
}

关键修改是在第12行:将{{template "t1"}}改为{{template "t1" .}}。这里的点号.表示将当前作用域的数据(即person{Name: "Prithvi"})传递给t1模板。

输出:

Prithvi the first template
Prithvi

如果你需要传递不同的数据给子模板,可以指定具体的变量:

const tmptTxt = `
{{- define "t1" }} {{.}} the first template {{ end -}}
{{template "t1" .Name}}
{{ .Name }}
`

在这个例子中,t1模板接收字符串类型的.Name值,而不是整个结构体。

回到顶部