在Go模板中请求上下文 [英] Request context in a Go template

查看:82
本文介绍了在Go模板中请求上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Go HTML模板中编写这样的条件片段:

  {{if isUserAdmin}} 
< a href/ admin / nuke>转到大红色核按钮< / a>
{{end}}

然而,这不是直接可能的,因为模板不是了解触发其执行的请求,因此无法确定用户是admin

是否有一些正常的方法来实现这一点?



事先我指出:




  • 我不想使用管道了解这些特定数据(请参阅关于此问题的其他问题

  • 我承认只有处理程序/控制器应该处理逻辑,而视图只应该执行渲染。但条件 {{if isUserAdmin}} 不是逻辑本身,它是利用控制器已经计算出的布尔值的必要结构。

  • Funcs 方法可以提供帮助,但目前还不够用于轻松定义特定方法 isUserAdmin()


解决方案

我会同意Darshan Computing,我认为从请求中传递信息的正确方式将在进行中。您可以将数据在要呈现的数据与上下文之间进行拆分,例如通过让你的模板数据结构嵌入它们两个,如果你想清楚地分开两个:

  type TemplateData struct {
* Content
* Context
}

给出这个例如。然后,您可以重用一些上下文/内容信息,具体取决于共享内容和特定查询的内容。


I would like to write such a conditional fragment in a Go HTML template :

  {{if isUserAdmin}}
     <a href"/admin/nuke">Go to the big red nuclear button</a>
  {{end}}

However, this is not directly possible because the template is not aware of the request that triggered its execution, so it cannot determine if the user is admin or not.

Is there some normal way to achieve this ?

In advance I point out that :

  • I do not want to use Pipelines for this specific data (see other question about this)
  • I acknowledge that only the handlers/controllers should deal with logic, and views should only do the rendering. But the condition {{if isUserAdmin}} is not logic itself, it's a necessary construct to leverage a boolean value already calculated by the controller.
  • The Funcs method can help, but is currently not lean enough for easily defining specific method isUserAdmin()

解决方案

I would agree with Darshan Computing, I think the proper way of passing information from the request would be in the pipeline. You can have your data being split between the data you want to render and the context, e.g. by having your template data structure embed them both if you want to clearly separate the two:

type TemplateData struct {
    *Content
    *Context
}

Which gives this for example. You can then reuse some of your context/content information depending on what is shared and what is query specific.

这篇关于在Go模板中请求上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆