将值传递给处理程序之外的html/template。

huangapple go评论88阅读模式
英文:

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),
    &quot;hello&quot;,
    &quot;world&quot;
  }
  err := t.Execute(w, &amp;data)  // t is the compiled template.
  if err != nil {
     // handle error
  }
}

You can use this in a template like this:

&lt;html&gt;
&lt;body&gt;
Here are some fields: {{.AFieldSpecificToThisView}} {{.AnotherViewField}}
{{if .IsAuthenticated}}The user is authenticated{{end}}
&lt;/body&gt;
&lt;/html&gt;

huangapple
  • 本文由 发表于 2016年12月21日 03:06:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/41249519.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定