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

时间:2015-01-24 08:15:00

标签: go

模板“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}}适用于网站正文,但在头部不起作用。

1 个答案:

答案 0 :(得分:2)

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

{{ template "head" . }}