变量在包含的模板中不起作用 (html/template)

Variables not working in included templates (html/template)

模板 "head" 插入 "index" 模板并使用一个变量 {{ .Title }}

Main.go:

package main

import (
    "html/template"
    "net/http"

    "github.com/julienschmidt/httprouter"
)

var (
    t = template.Must(template.ParseGlob("templates/*.tpl"))
)

type Page struct {
    Title string
    Desc  string
}

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    index := Page{Title: "This is title", Desc: "Desc"}
    t.ExecuteTemplate(w, "index", index)
}

func main() {
    router := httprouter.New()
    router.GET("/", Index)

    http.ListenAndServe(":8080", router)
}

Index.tpl:

{{ define "index" }}

<!DOCTYPE html>
<html lang="en">
    {{ template "head" }}
<body>
    <h1>Main info:</h1>
    Title: {{ .Title }}
    Desc: {{ .Desc }}
</body>
</html>


{{ end }}

head.tpl:

{{ define "head" }}

<head>
    <meta charset="UTF-8">
    <title>{{ .Title }}</title>
</head>

{{ end }}

我明白了 html:

<!DOCTYPE html>
<html lang="en">


<head>
    <meta charset="UTF-8">
    <title></title>
</head>


<body>
    <h1>Main info:</h1>
    Title: This is title
    Desc: Desc
</body>
</html>

变量 {{ .Title }} 适用于网站正文,但不适用于网站头部。

您必须将变量传递给模板:

{{ template "head" . }}