登录
首页 >  Golang >  Go问答

我可以从嵌套模板访问顶级模板变量吗?

来源:stackoverflow

时间:2024-02-12 14:21:23 418浏览 收藏

你在学习Golang相关的知识吗?本文《我可以从嵌套模板访问顶级模板变量吗?》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

假设我有一个带有这样的嵌套子模板的模板。演示链接

package main

import (
    "os"
    "text/template"
)

type person struct {
    firstname  string
    secondname string
}

type document struct {
    docname string
    people  []person
}

const document = `
document name: {{.docname}}

{{range $person:=.people}}
{{template "person" $person}}
{{end}}

{{- define "person"}}
person name is: {{.firstname}} {{.secondname}}
{{end}}
`

func main() {

    d := document{
        docname: "first try",
        people: []person{
            {"brian", "kernighan"},
            {"dennis", "ritchie"},
        },
    }

    t := template.must(template.new("document").parse(document))

    err := t.execute(os.stdout, d)
    if err != nil {
        panic(err)
    }

}

一切正常,但现在我想设置一些文档范围的变量来更改所有模板及其子模板中的行为。像这样(不起作用,恐慌)。演示链接

type Person struct {
    FirstName  string
    SecondName string
}

type Document struct {
    DocName string
    People  []Person

    SwitchNameOrder bool
}

const document = `
Document name: {{.DocName}}

{{range $person:=.People}}
{{template "person" $person}}
{{end}}

{{- define "person"}}
{{if $.SwitchNameOrder}} // <---- panic here
Person name is: {{.SecondName}} {{.FirstName}}
{{else}}
Person name is: {{.FirstName}} {{.SecondName}}
{{end}}
{{end}}
`

怎么做呢?可能吗?


正确答案


您可以做的一件事是使用模板函数将传递到子模板的变量与父模板中的变量“合并”。

type person struct {
    firstname  string
    secondname string
}

type document struct {
    docname string
    people  []person

    switchnameorder bool
}

func personwithdocument(p person, d document) interface{} {
    return struct {
        person
        document document
    }{p, d}
}

t := template.must(template.new("document").funcs(template.funcmap{
    "personwithdocument": personwithdocument,
}).parse(document))

然后在模板中您将执行以下操作:

const document = `
Document name: {{.DocName}}

{{range $person:=.People}}
{{template "person" (personWithDocument $person $) }}
{{end}}

{{- define "person"}}
{{if .Document.SwitchNameOrder}}
Person name is: {{.SecondName}} {{.FirstName}}
{{else}}
Person name is: {{.FirstName}} {{.SecondName}}
{{end}}
{{end}}
`

https://play.golang.org/p/YorPsMdr9g_H

到这里,我们也就讲完了《我可以从嵌套模板访问顶级模板变量吗?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>