templates - 嵌套 golang 模板中的变量

标签 templates go

我想在 golang 模板中定义变量,而不是在二进制文件中,这样就不需要重新编译。

在 Go 中,我设置了一些变量:

var animals = map[string]string{
    "spirit_animal":    "cat",
    "spirit_predator":  "dog",
}

我用这个执行模板:t.ExecuteTemplate(w, "main", variables)它将这些变量传递给模板。

现在我想将这些变量从 go 中取出到“主”模板中。
{{$spirit_animal:="cat"}} {{$spirit_animal}}

我这样称呼子模板:
{{ template "navbar" . }}

问题是嵌套模板(子模板)似乎无法访问任何变量。

来自 documentation , “模板调用不会从其调用点继承变量。”阅读“文本/模板”的文档,听起来变量可能无法在嵌套模板中使用。

关于如何将这些变量从二进制文件中取出并放入不需要在更改时重新编译的嵌套模板可访问的单个文本位置的任何建议?

最佳答案

你确实可以!您只需要将变量传递到嵌套模板中。
您引用的文档是关于模板如何无法从 go 过程中读取变量的,除非您明确地将它们传入。
同样,嵌套模板将接受您传递给它们的任何内容,仅此而已。
来自 https://golang.org/pkg/text/template/#hdr-Actions

{{template "name"}}
    The template with the specified name is executed with nil data.

{{template "name" pipeline}}
    The template with the specified name is executed with dot set
    to the value of the pipeline.
这是一个基于您的提示的快速示例:
package main

import (
    "os"
    "text/template"
)

func main() {
    var animals = map[string]string{
        "spirit_animal":   "cat",
        "spirit_predator": "dog",
    }

    const letter = `
{{define "echo"}}Inside a template, I echo what you say: {{.}}{{end}}
{{define "predator"}}Inside a template, I know that your predator is: {{.spirit_predator}}{{end}}

Your spirit animal is: {{.spirit_animal}}

{{template "predator" . }}

{{template "echo" .spirit_animal }}`

    t := template.Must(template.New("letter").Parse(letter))
    _ = t.Execute(os.Stdout, animals)
}
https://play.golang.org/p/3X7IQasWlsR

关于templates - 嵌套 golang 模板中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39254898/

相关文章:

c++ - 为什么递归可变参数模板不能按预期工作?

c++ - SFINAE 离开了一个拷贝构造函数

javascript - Angular : Variable template inside directive

caching - Go 是否缓存 DNS 查找?

go - 如何获得下一个IP地址?

c++ - 将lambda参数传递给没有中间变量的std::function参数

c++ - 传入的模板类型与基本类型或对象的比较

json - Golang net/http 请求 Body 总是空的

json - 如何从 Go 动态创建 JSON 结构?

go - 为什么这段代码会停止?