Go template function

后端 未结 3 2031
你的背包
你的背包 2021-02-05 02:26

It noticed a weird thing with Go templates when I try to use Funcs and FuncMap. The following code works as expected:

buffer := bytes.N         


        
3条回答
  •  走了就别回头了
    2021-02-05 03:10

    Sonia's answer is technically correct but left me even more confused. Here's how I eventually got it working:

    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)
    }
    

    The name of the template is the bare filename of the template, not the complete path. Execute will execute the default template provided it's named to match, so there's no need to use ExecuteTemplate.

    In this case, _base.html file is the outermost container, eg:

    
    
    

    {{ template "title" }}

    {{ template "content" }}

    while home.html defines the specific parts:

    {{ define "title" }}Home{{ end }}
    
    {{ define "content" }}
    Stuff
    {{ end }}
    

提交回复
热议问题