Closed sh4nks closed 3 years ago
I have created a minimal reproducible example here: https://github.com/sh4nks/go-playground
Hmm, this is interesting. I hadn't thought about using the HTMLOptions
for functions... I had only used that for adding in layouts. So this isn't working because the templates are compiled when the app starts up for the first time. This is a nice performance win, but it comes with the trade off not allowing dynamic functions per render. (When compiling the templates it sees the function call but has no reference to it at that point since that function is only defined at the request level) A couple ways you could potentially get around this:
csrfField
value as a data param instead (just like you passed Content
in your example project)render.Options
struct)If you have other ideas, let me know and we'll see what we can work out.
Ah of course -- I hadn't thought about passing the csrfField as a data param. Thanks!
I am just curious - how should the feature added in PR #81 be used?
If I'm not mistaken, you can define a global template function (inside render.Options
) and then override it in the request. Something like this:
func main() {
rendr := render.New(render.Options{
Funcs: []template.FuncMap{
{
"myFunc": func() string {
return "My function"
},
},
},
})
// ...
router.Get("/", func(w http.ResponseWriter, r *http.Request) {
htmlOpts := render.HTMLOptions{
Funcs: template.FuncMap{
"myFunc": func() string {
return "My function from within a request!"
},
},
}
rendr.HTML(w, 200, "main", map[string]string{"Content": "Test Content"}, htmlOpts)
})
// ...
}
Yes that works -- thanks for helping out a Go newbie!
Hi,
I needed to add a specific function which require the http.Request and found out that I could add them via the HTMLOptions struct. However, it doesn't seem to work for me.
This is what I got:
and in my template I am trying to call it like this:
It always errors with
Upon further investigation I found out that the functions do get registered here:
but don't seem to be available in the template?
I am kinda new to Go so I am not sure if either I am doing something wrong or if this is a bug?