Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go template function

It noticed a weird thing with Go templates when I try to use Funcs and FuncMap. The following code works as expected:

buffer := bytes.NewBufferString("")  funcMap := template.FuncMap{     "label": strings.Title, }  t, _ := template.New("alex").Funcs(funcMap).Parse("{{label \"alex\"}}")   t.Execute(buffer, "")  return string(buffer.Bytes()) //=> "Alex" 

But when I try to put the template in a file, it does not work (Execute() says: "alex" is an incomplete or empty template):

t, _ := template.New("alex").Funcs(funcMap).ParseFiles("template.html")  

With template.html:

{{label \"alex\"}} 

Any idea why ? Is this a bug ? Are there simpler ways to use methods/functions in templates ?

like image 528
Blacksad Avatar asked Apr 17 '12 21:04

Blacksad


People also ask

How do you call a function in Go template?

According to the documentation, you can call any method which returns one value (of any type) or two values if the second one is of type error . In the later case, Execute will return that error if it is non-nil and stop the execution of the template. Thanks, it works !

What is go template language?

Go's template is designed to be extended by developers, and provides access to data objects and additional functions that are passed into the template engine programmatically. This tutorial only uses functions universally provided in the text/template package, and does not discuss the specifics of data access.


1 Answers

ParseFiles could probably use better documentation. A template object can have multiple templates in it and each one has a name. If you look at the implementation of ParseFiles, you see that it uses the filename as the template name inside of the template object. So, name your file the same as the template object, (probably not generally practical) or else use ExecuteTemplate instead of just Execute.

like image 174
Sonia Avatar answered Oct 22 '22 16:10

Sonia