multitemplate icon indicating copy to clipboard operation
multitemplate copied to clipboard

Handle passing functions to templates?

Open jonathanGB opened this issue 8 years ago • 7 comments

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!

jonathanGB avatar Feb 23 '17 05:02 jonathanGB

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.

BenKnigge avatar Oct 10 '17 07:10 BenKnigge

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 :(

Macilias avatar Jul 04 '18 14:07 Macilias

Any updates?

nanom1t avatar Jan 04 '19 10:01 nanom1t

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>`)

sergolius avatar Jan 24 '19 13:01 sergolius

How does any of those methods make the registered functions available within the (HTML) templates, @sergolius?

asbjornu avatar Jul 27 '22 15:07 asbjornu

@asbjornu AddFromFilesFuncs, AddFromStringsFuncs uses Go's package html/template functionality of Template creation and extension. AddFromStringsFuncs:

tmpl := template.New(name).Funcs(funcMap)

sergolius avatar Jul 27 '22 15:07 sergolius

@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!

asbjornu avatar Jul 27 '22 16:07 asbjornu