multitemplate
multitemplate copied to clipboard
Handle passing functions to templates?
I know it's possible to pass helper functions to normal html/template
, but is it possible with this wrapper? If not, it would be cool to have it.
Thanks!
I'm also trying to figure out how to get this working. No matter what I do I end up getting an error that the function is not defined.
My guess is that the randerer treats each comment without leading . as function. This really is an issue, since it interferes with 3rd party stuff including {{tobereplaced}} stuff like dropbox for example. The only solution I could think of here would be to change the delimiter for mulitemplate, but the expample from gin-gonic: router.Delims("{[{", "}]}") seam not to have any effect :(
Any updates?
There is two variants how to add Funcs:
- AddFromFilesFuncs;
- AddFromStringsFuncs.
Lets use
.../multitemplate/example/advanced/example.go:45
as base:
r.AddFromFiles(filepath.Base(include), files...)
AddFromFilesFuncs:
r.AddFromFilesFuncs(filepath.Base(include), template.FuncMap{}, files...)
AddFromStringsFuncs:
r.AddFromStringsFuncs("tmpl-name", template.FuncMap{}, `<script>alert(1);</script>`)
How does any of those methods make the registered functions available within the (HTML) templates, @sergolius?
@asbjornu AddFromFilesFuncs
, AddFromStringsFuncs
uses Go's package html/template
functionality of Template creation and extension.
AddFromStringsFuncs:
tmpl := template.New(name).Funcs(funcMap)
@sergolius, ah, I see. I managed to get this to work:
r := multitemplate.NewRenderer()
r.AddFromFilesFuncs("entry", template.FuncMap{
"my_func": func() string {
return "xyz"
},
}, "views/base.html", "views/entry.html")
I am now able to use {{ my_func }}
in entry.html
, which outputs xyz
. Thanks!