英文:
Passing values to html/template outside of handler
问题
我想将包含所有管理员/系统值的结构体传递给使用Go中的html/template解析的视图。例如,我想默认情况下将.IsAuthenticated和.IsAdmin传递给我的视图,而无需通过处理程序显式传递。
是否可以使这些值默认始终可用,而无需通过处理程序传递?我希望通过处理程序传递表单值和其他用户生成的内容。
英文:
I would like to pass a struct which contains all of my admin/system values to my view, which is parsed using html/template in Go. For example, I would like to give .IsAuthenticated and .IsAdmin to my view by default, without explicitly passing it through the handler.
Is it possible to make these values always available by default, without passing through a handler? I would like to pass form values and other user generated content through the handler.
答案1
得分: 2
模板无法直接访问admin/system结构体,除非应用程序将该值传递给模板。通过每个视图类型中的匿名字段传递值是一种方便的方法。以下是一个示例:
假设AdminStuff
是包含管理员和系统数据的结构体,getAdminSystemStuff(*http.Request)
是一个从请求中获取结构体指针的函数,可以像这样定义视图数据:
func myHandler(w http.Response, r *http.Request) {
var data = struct {
*AdminSystemStuff
AFieldSpecificToThisView string
AnotherViewField string
}{
getAdminSystemStuff(r),
"hello",
"world"
}
err := t.Execute(w, &data) // t是编译后的模板。
if err != nil {
// 处理错误
}
}
可以在模板中这样使用:
<html>
<body>
这里有一些字段:{{.AFieldSpecificToThisView}} {{.AnotherViewField}}
{{if .IsAuthenticated}}用户已经通过身份验证{{end}}
</body>
</html>
英文:
It is not possible for the template to access the admin/system struct without the application passing the value to the template. A convenient way to to pass the value is through an anonymous field in each view type. Here's an example:
Assuming that AdminStuff
is the struct containing your admin and system data and getAdminSystemStuff(*http.Request)
is a function that gets a pointer to the struct from a request, define the view data like this:
func myHandler(w http.Response, r *http.Request) {
var data = struct {
*AdminSystemStuff
AFieldSpecificToThisView string
AnotherViewField string
}{
getAdminSystemStuff(r),
"hello",
"world"
}
err := t.Execute(w, &data) // t is the compiled template.
if err != nil {
// handle error
}
}
You can use this in a template like this:
<html>
<body>
Here are some fields: {{.AFieldSpecificToThisView}} {{.AnotherViewField}}
{{if .IsAuthenticated}}The user is authenticated{{end}}
</body>
</html>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论