douju9272 2013-08-18 19:24
浏览 68

在Go模板中请求上下文

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()
  • 写回答

3条回答 默认 最新

  • douweng1935 2013-08-18 19:27
    关注

    Here is a working solution attempt (link to Playground) using Funcs to overwrite "isAdmin", after template compilation but before each execution (thanks to Valentin CLEMENT in other question).

    But it has several flaws :

    • It is weird to declare a dummy empty "isAdmin" function before template compilation.
    • (Using Funcs several times is painful because I cannot just overwrite a single method, I have to provide a complete FuncMap with all the functions) edit : in fact previous funcs are not lost, i was wrong about that.
    • It is inherently not thread-safe and will fail when several goroutines alter and execute the same template
    评论

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗