Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request context in a Go template

Tags:

templates

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()
like image 777
Deleplace Avatar asked Dec 26 '22 22:12

Deleplace


1 Answers

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.

like image 81
val Avatar answered Jan 11 '23 21:01

val