去模板功能

Bla*_*sad 29 go go-templates

当我尝试使用Funcs和时,它注意到Go模板有一个奇怪的东西FuncMap.以下代码按预期工作:

buffer := bytes.NewBufferString("")

funcMap := template.FuncMap{
    "label": strings.Title,
}

t, _ := template.New("alex").Funcs(funcMap).Parse("{{label \"alex\"}}") 

t.Execute(buffer, "")

return string(buffer.Bytes()) //=> "Alex"
Run Code Online (Sandbox Code Playgroud)

但是当我尝试将模板放在一个文件中时,它不起作用(Execute()说:) "alex" is an incomplete or empty template:

t, _ := template.New("alex").Funcs(funcMap).ParseFiles("template.html") 
Run Code Online (Sandbox Code Playgroud)

使用template.html:

{{label \"alex\"}}
Run Code Online (Sandbox Code Playgroud)

知道为什么吗?这是一个错误吗?是否有更简单的方法在模板中使用方法/功能?

Son*_*nia 32

ParseFiles可能会使用更好的文档.模板对象中可以包含多个模板,每个模板都有一个名称.如果查看ParseFiles的实现,您会看到它使用文件名作为模板对象内部的模板名称.因此,将文件命名为与模板对象相同(可能通常不实用),或者使用ExecuteTemplate而不是Execute.


Mar*_*ing 16

索尼娅的回答在技术上是正确的,但让我更加困惑.这是我最终如何运作:

t, err := template.New("_base.html").Funcs(funcs).ParseFiles("../view/_base.html", "../view/home.html")
if err != nil {
    fmt.Fprint(w, "Error:", err)
    fmt.Println("Error:", err)
    return
}
err = t.Execute(w, data)
if err != nil {
    fmt.Fprint(w, "Error:", err)
    fmt.Println("Error:", err)
}
Run Code Online (Sandbox Code Playgroud)

模板的名称是模板的裸文件名,而不是完整路径.Execute将执行默认模板,前提是它的命名匹配,因此无需使用ExecuteTemplate.

在这种情况下,_base.htmlfile是最外层的容器,例如:

<!DOCTYPE html>
<html><body>
<h1>{{ template "title" }}</h1>
{{ template "content" }}
</body></html>
Run Code Online (Sandbox Code Playgroud)

同时home.html定义具体部分:

{{ define "title" }}Home{{ end }}

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