Golang.将数据发送到模板不起作用

Raz*_*zip -1 go

我想知道将任何数据发送到模板(html /模板包)的真正方法是什么?我的代码如下:

var templates = template.Must(template.ParseFiles(
    path.Join(this.currentDirectory, "views/base.html"),
    path.Join(this.currentDirectory, "views/main/test.html"),
))

templates.Execute(response, map[string]string{
    "Variable": "????!",
})
Run Code Online (Sandbox Code Playgroud)

这是模板:

{{define "content"}}
{{ .Variable }}
{{end}}
Run Code Online (Sandbox Code Playgroud)

我会很感激的!

Jim*_*imB 5

您的模板有一个名称,"content"因此您需要专门执行该模板.

templates.ExecuteTemplate(os.Stdout, "content", map[string]string{
    "Variable": "????!",
})
Run Code Online (Sandbox Code Playgroud)

你可能没有解析你的想法.从template.ParseFiles文档(强调我的)

返回的模板名称将包含第一个文件的(基本)名称和(已解析)内容

尝试使用:

t, err := template.New("base").ParseFiles("base.html", "test.html")
if err != nil { ... }
t.Execute(response, variables)
Run Code Online (Sandbox Code Playgroud)

如果它有帮助,这里是一个游乐场的例子.