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

Max*_*Lis 2 go

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

主要.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)
}
Run Code Online (Sandbox Code Playgroud)

索引.tpl:

{{ define "index" }}

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


{{ end }}
Run Code Online (Sandbox Code Playgroud)

head.tpl:

{{ define "head" }}

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

{{ end }}
Run Code Online (Sandbox Code Playgroud)

我得到这个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>
Run Code Online (Sandbox Code Playgroud)

变量 {{ .Title }} 在网站正文中起作用,但在头部中不起作用。

top*_*kip 5

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

{{ template "head" . }}
Run Code Online (Sandbox Code Playgroud)