我的设置:
base.tmpl
{{define "base"}} ...basic hmtl boilerplate ...{{end}}
{{define "post"}}
{{.ID}} {{.Username}} etc...
{{if $.User.Admin}}
<...admin controls...>
{{end}}
{{end}}
index.tmpl
{{template "base" . }}
{{define "content"}}
Stuff......
{{range .Posts }}
{{template "post" . }}
{{end}}
{{end}}
但是我得到了
$。User.Admin不是db.Post的字段
如何从&#34; global&#34;中获取值?模板中的点值是否给定? $。显然不起作用。
我只是在该范围内发布帖子,但我添加了一个新页面来查看各个帖子,并且不想更新帖子单独显示的每个区域。
更新:模板执行如此
func Index(rw http.ResponseWriter, req *http.Request) {
g := GetGlobal(rw, req) // Gets logged in user info, adds branch/version info etc
... Get posts from the DB ...
if err := Templates["index.tmpl"].Execute(rw, g); err != nil {
Log.Println("Error executing template", err.Error())
}
}
Global struct看起来像:
type Global struct {
User db.User
Users []db.User
EditUser db.User
Session *sessions.Session
Error error
Posts []db.Post
Post db.Post
DoRecaptcha bool
Host string
Version string
Branch string
}
模板加载如下:
Templates[filename] = template.Must(template.ParseFiles("templates/"+filename, "templates/base.tmpl"))
答案 0 :(得分:3)
调用模板会创建一个新范围:
模板调用不会从其调用点继承变量。
所以你有三个选择:
创建一个通过闭包引用变量的函数(isAdmin
):
template.New("test").Funcs(map[string]interface{}{
"isAdmin": func() bool {
return true // you can get it here
},
}).Parse(src)
这种方法的缺点是你每次都必须解析模板。
创建一个新函数,该函数可以构造一个对父项具有引用的帖子,而无需修改原始数据。例如:
template.New("test").Funcs(map[string]interface{}{
"pair": func(x, y interface{}) interface{} {
return struct { First, Second interface{} } { x, y }
},
}).Parse(src)
你可以像这样使用它:
{{range .Posts }}
{{template "post" pair $ . }}
{{end}}
另一种选择是制作dict
函数:Calling a template with several pipeline parameters