英文:
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 }}在网页正文中起作用,但在头部不起作用。
英文:
The template "head" inserted on "index" template and use one variable {{ .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 }}
I get this 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>
Variable {{ .Title }} works on site body, but doesn't work in head.
答案1
得分: 5
你必须将变量传递给模板:
{{ template "head" . }}
英文:
You have to pass the variables to the template:
{{ template "head" . }}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论