function / method call inside of template

2,832 views
Skip to first unread message

mschlimp

unread,
Oct 24, 2011, 10:26:15 AM10/24/11
to golang-nuts
Hi,

it is possible to call a function inside a template?
Something like:

t1, _ := template.New("test2").Parse("a {{.FuncName}} e")

and

func FuncName() string{
return "alf"
}


Thanks
Marcel

roger peppe

unread,
Oct 24, 2011, 10:42:09 AM10/24/11
to mschlimp, golang-nuts
looks like you can't.("F is not a method but has arguments")

given that you can already call methods on
objects with dynamically known type, i don't see that
there's any particular security reason to disallow this,
but there may be other reasons i haven't thought of

perhaps you might raise an issue.

André Paquet

unread,
Oct 24, 2011, 11:18:23 AM10/24/11
to golan...@googlegroups.com
funcs := template.FuncMap{"FuncName" : FuncName}
t1, _ := template.New("test2")
t1.Funcs(funcs)
t1.Parse("a {{.FuncName}} e") 

roger peppe

unread,
Oct 24, 2011, 11:28:08 AM10/24/11
to golan...@googlegroups.com
2011/10/24 André Paquet <andre....@gmail.com>:

yes, you can do it by explicitly naming the function,
but you can't dynamically choose a function to call,
which might be useful (you can make a map look like a type with
methods this way, for example).

package main

import (
"fmt"
"os"
"template"
)

func foo(s string) string {
return "foo: " + s
}

func main() {
t := template.Must(template.New("name").Parse(`{{.F "arg"}}`))
v := struct{F func(string) string}{foo}
e := t.Execute(os.Stdout, v)
fmt.Printf("returned err %v\n", e)
}

André Paquet

unread,
Oct 24, 2011, 11:34:27 AM10/24/11
to golan...@googlegroups.com
Sorry, I misunderstood your point.

Marcel Schlimper

unread,
Oct 24, 2011, 12:09:00 PM10/24/11
to roger peppe, golang-nuts

Is there a other way to put dynamic content to the template....
The ideale Is to add html snippets by functions Into the template

Am 24.10.2011 16:42 schrieb "roger peppe" <rogp...@gmail.com>:

roger peppe

unread,
Oct 24, 2011, 12:23:05 PM10/24/11
to Marcel Schlimper, golang-nuts

if you can decide on a single signature for your snippet functions,
then it's easy. for instance:

package main

import (
"fmt"
"os"
"template"
)

type Snippet func(arg string) string
func (s Snippet) Call(arg string) string {
return s(arg)
}

func foo(s string) string {
return "foo: " + s
}

func main() {
t := template.Must(template.New("name").Parse(`{{.F.Call "arg"}}`))
v := struct{F Snippet}{foo}
e := t.Execute(os.Stdout, v)
fmt.Printf("\nreturned err %v\n", e)
}

Marcel Schlimper

unread,
Oct 24, 2011, 3:55:03 PM10/24/11
to roger peppe, golang-nuts
Ok,

thanks for the tip.
I will have a trial to use it for writing a set of html render methods for


thanks.
Marcel
Reply all
Reply to author
Forward
0 new messages