text/template: Can't call method/function with 0 results.

472 views
Skip to first unread message

Johnny Jacobs

unread,
Apr 9, 2021, 2:05:33 PM4/9/21
to golang-nuts
Hello all,

Is there any reason you can't use a custom function with no return value in Go templates?

You get a "Can't call method/function with 0 results." if you try to call such a function. FuncMap requires functions to either return a value, or a value plus an error.

Is there any reason, technical or otherwise, for these restrictions? Variables assignment and many Action clauses don't give back values, so it doesn't seem like it breaks convention.

I might file an issue for this if nothing meaningful is brought up here.

Best,
Johnny

Thomas Bushnell BSG

unread,
Apr 9, 2021, 2:14:17 PM4/9/21
to Johnny Jacobs, golang-nuts
I find the current behavior clearer. What would you like a no-valued function to insert in the template? Even if it was the zero value, that could be the string-typed zero value, or the int-typed zero value, and so forth.

It could be defined, but why not make it explicit if you want it to insert nothing, and return the empty string?

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/fdb52e84-0cea-4269-9016-cc1d5064cc5bn%40googlegroups.com.

aind...@gmail.com

unread,
Apr 9, 2021, 2:19:30 PM4/9/21
to golang-nuts
I believe functions are meant to be used as part of a pipeline, so having
1 value (+ error) makes it so the pipeline only stops execution on an error.
I personally have not found a use for void functions, and it makes it easier
to visualize the template execution model.

Johnny Jacobs

unread,
Apr 9, 2021, 2:25:13 PM4/9/21
to aind...@gmail.com, golang-nuts
I'm mostly thinking of functions with side-effects, much like {{ $var := "val" }}. It doesn't make much sense for these to return anything.

Not allowing 0-valued functions limits functions you can call on objects in templates as well. For example, a trivial map implementation:
type MyMap map[string]interface{}
func (m MyMap) Set(key string, val interface{}) { m[key] = val }

And then in your function map:
"Map": func map() MyMap { return make(MyMap) }

You can't actually use Set in a template as it has void return.

--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/xAvfWunrHss/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/41190a31-3151-4a5a-b9b8-631198dca58fn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages